-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevalPrefix.c
More file actions
106 lines (59 loc) · 1.28 KB
/
evalPrefix.c
File metadata and controls
106 lines (59 loc) · 1.28 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
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<ctype.h>
#include<string.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 evaluatePrefix(char prefix[]){
Stack* stack = createStack(100);
strrev(prefix);
int i=0;
while(prefix[i] != '\0'){
char ch = prefix[i];
if(isalnum(ch)){
int n = ch - '0';
push(n,stack);
}else{
int n1 = pop(stack);
int n2 = pop(stack);
int ans = performOp(n1,ch,n2);
push(ans,stack);
}
i++;
}
printf("Final result is %d",pop(stack));
}
int main(){
char prefix[] = "+9*23";
evaluatePrefix(prefix);
}