forked from Septchi/CS_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathin2postfix.c
More file actions
145 lines (129 loc) · 2.93 KB
/
Copy pathin2postfix.c
File metadata and controls
145 lines (129 loc) · 2.93 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#define s 32
typedef struct{
char stk[s];
int tos;
} Stack;
Stack newStack(){
Stack stack;
stack.tos = -1;
return stack;
}
char pop(Stack* stack){
char data = stack->stk[stack->tos];
stack->tos--;
return data;
}
void push(Stack* stack, char data){
stack->tos++;
stack->stk[stack->tos] = data;
}
char peek(Stack stack){
return stack.stk[stack.tos];
}
bool isFull(int tos){
bool full = false;
if(tos == s -1)
full = true;
return full;
}
bool isEmpty(int tos){
bool empty = false;
if(tos == -1)
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[s/2];
char output[s/2];
printf("enter postfix equation: ");
fgets(input, s/2, stdin);
bool full, empty;
char op;
int i = 0;
int j = 0;
float n1, n2, res;
Stack stack = newStack();
while((op = input[i++]) != '\n'){
if(isdigit(op)){
output[j++] = op;
continue;
}
empty = isEmpty(stack.tos);
if(empty){
full = isFull(stack.tos);
if(!full)
push(&stack, op);
else{
printf("stack full\n");
}
}
else if(op == '('){
full = isFull(stack.tos);
if(!full)
push(&stack, op);
else{
printf("stack full\n");
}
}
else if(op == ')'){
empty = isEmpty(stack.tos);
while(!empty){
if(peek(stack) != '('){
output[j++] = pop(&stack);
}
else
break;
empty = isEmpty(stack.tos);
}
}
else{
if(prec(op) >= prec(peek(stack))){
full = isFull(stack.tos);
if(!full)
push(&stack, op);
else{
printf("stack full\n");
}
continue;
}
empty = isEmpty(stack.tos);
while(!empty){
if(prec(op) < prec(peek(stack))){
output[j++] = pop(&stack);
empty = isEmpty(stack.tos);
}
else{
full = isFull(stack.tos);
if(!full)
push(&stack, op);
else{
printf("stack full\n");
}
break;
}
}
}
}
empty = isEmpty(stack.tos);
while(!empty){
output[j++] = pop(&stack);
empty = isEmpty(stack.tos);
}
printf("%s", output);
}