-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix.c
65 lines (65 loc) · 1.15 KB
/
postfix.c
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
#include<stdio.h>
#include<string.h>
#define MAX 50
int stack[MAX];
char post[MAX];
int top=-1;
void pushstack(int tmp);
void evaluate(char c);
void main()
{
int i,l;
printf("Insert a postfix notation :: ");
gets(post);
l=strlen(post);
for(i=0; i<l; i++)
{
if(post[i]>='0' && post[i]<='9')
{
pushstack(i);
}
if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
post[i]=='/' || post[i]=='^')
{
evaluate(post[i]);
}
}
printf("\n\nResult :: %d",stack[top]);
}
void pushstack(int tmp)
{
top++;
stack[top]=(int)(post[tmp]-48);
}
void evaluate(char c)
{
int a,b,ans;
a=stack[top];
stack[top]='\0';
top--;
b=stack[top];
stack[top]='\0';
top--;
switch(c)
{
case '+':
ans=b+a;
break;
case '-':
ans=b-a;
break;
case '*':
ans=b*a;
break;
case '/':
ans=b/a;
break;
case '^':
ans=b^a;
break;
default:
ans=0;
}
top++;
stack[top]=ans;
}