-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathin2postfixL.c
More file actions
116 lines (103 loc) · 2.23 KB
/
Copy pathin2postfixL.c
File metadata and controls
116 lines (103 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct node* nodeptr;
struct node{
char val;
nodeptr next;
};
char pop(nodeptr* head){
char data = (*head)->val;
nodeptr temp = *head;
*head = temp->next;
free(temp);
return data;
}
void push(nodeptr* head, char data){
nodeptr node = malloc(sizeof(nodeptr));
node->val = data;
node->next = *head;
*head = node;
}
char peek(nodeptr head){
return head->val;
}
bool isEmpty(nodeptr head){
bool empty = false;
if(head == NULL)
empty = true;
return empty;
}
int prec(char op){
switch(op){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 0;
}
return -1;
}
int main(){
char input[16];
char output[16];
printf("enter postfix equation: ");
fgets(input, 16, stdin);
bool full, empty;
char op;
int i = 0;
int j = 0;
float n1, n2, res;
nodeptr head = NULL;
while((op = input[i++]) != '\n'){
if(isdigit(op)){
output[j++] = op;
continue;
}
empty = isEmpty(head);
if(empty){
push(&head, op);
}
else if(op == '('){
push(&head, op);
}
else if(op == ')'){
empty = isEmpty(head);
while(!empty){
if(peek(head) != '('){
output[j++] = pop(&head);
}
else
break;
empty = isEmpty(head);
}
}
else{
if(prec(op) >= prec(peek(head))){
push(&head, op);
continue;
}
empty = isEmpty(head);
while(!empty){
if(prec(op) < prec(peek(head))){
output[j++] = pop(&head);
empty = isEmpty(head);
}
else{
push(&head, op);
break;
}
}
}
}
empty = isEmpty(head);
while(!empty){
output[j++] = pop(&head);
empty = isEmpty(head);
}
printf("%s", output);
}