-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevalPostfix.c
More file actions
101 lines (57 loc) · 1.25 KB
/
evalPostfix.c
File metadata and controls
101 lines (57 loc) · 1.25 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
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<ctype.h>
typedef struct Stack{
int size;
int top;
char *arr;
}Stack;
Stack* createStack(int size){
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->size = size;
stack->top = -1;
stack->arr = (char*)malloc(sizeof(char)*size);
return stack;
}
void push(int val,Stack* stack){
stack->arr[++stack->top] = val;
}
char pop(Stack* stack){
return stack->arr[stack->top--];
}
int isEmpty(Stack* stack){
return stack->top == -1;
}
void peek(Stack* stack){
printf("%c ", stack->arr[stack->top]);
}
int performOp(int a,char op,int b){
if(op == '*') return a*b;
if(op == '/') return a/b;
if(op == '+') return a+b;
if(op == '-') return a-b;
else return -1;
}
void evaluatePostfix(char postfix[]){
Stack* stack = createStack(100);
int i=0;
while(postfix[i] != '\0'){
char ch = postfix[i];
if(isalnum(ch)){
int n = ch - '0';
push(n,stack);
}else{
int n1 = pop(stack);
int n2 = pop(stack);
int ans = performOp(n2,ch,n1);
push(ans,stack);
}
i++;
}
printf("Final result is %d",pop(stack));
}
int main(){
char postfix[] = "53+82-*";
evaluatePostfix(postfix);
}