-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpostfix.c
More file actions
119 lines (105 loc) · 2.33 KB
/
Copy pathpostfix.c
File metadata and controls
119 lines (105 loc) · 2.33 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
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#define s 32
typedef struct{
int stk[s];
int tos;
} Stack;
Stack newStack(){
Stack stack;
stack.tos = -1;
return stack;
}
int pop(Stack* stack){
int data = stack->stk[stack->tos];
stack->tos--;
return data;
}
void push(Stack* stack, int data){
stack->tos++;
stack->stk[stack->tos] = data;
}
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 main(){
char input[s/2];
printf("enter postfix equation: ");
fgets(input, s/2, stdin);
bool full, empty;
char op;
int i = 0;
float n1, n2, res;
Stack stack = newStack();
while((op = input[i++]) != '\n'){
printf("op: %c\n", op);
if(isdigit(op)){
res = op - '0';
full = isFull(stack.tos);
if(!full)
push(&stack, res);
else{
printf("stack full\n");
return 0;
}
}
else{
empty = isEmpty(stack.tos);
if(!empty)
n1 = pop(&stack);
else{
printf("stack empty\n");
return 0;
}
empty = isEmpty(stack.tos);
if(!empty)
n2 = pop(&stack);
else{
printf("stack empty\n");
return 0;
}
switch(op){
case '+':
res = n1 + n2;
break;
case '-':
res = n2 - n1;
break;
case '*':
res = n1 * n2;
break;
case '/':
res = n2 / n1;
break;
}
full = isFull(stack.tos);
if(!full)
push(&stack, res);
else{
printf("stack full\n");
}
}
}
empty = isEmpty(stack.tos);
if(!empty)
res = pop(&stack);
else{
printf("stack empty\n");
return 0;
}
empty = isEmpty(stack.tos);
if(empty)
printf("Result is %.2f\n", res);
else
printf("Error");
}