-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix_eval.c
89 lines (85 loc) · 1.46 KB
/
postfix_eval.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *next;
}*top=NULL;
void push(int x)
{
struct node *t=(struct node*)malloc(sizeof(struct node));
if(t==NULL)
printf("Stack overflow\n");
else
{
t->data=x;
t->next=top;
top=t;
}
}
int pop()
{
struct node *p;
char x=-1;
if(top==NULL)
printf("Underflow\n");
else
{
p=top;
top=top->next;
x=p->data;
free(p);
}
return x;
}
int stacktop()
{
if(top)
return top->data;
else
return -1;
}
int isEmpty()
{
if(top==NULL)
return 1;
else
return 0;
}
int isoperand(char ch)
{
if((ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'))
return 0;
else
return 1;
}
int post_eval(char *a)
{
int i,j,x1,x2,r;
for(i=0;a[i]!='\0';i++)
{
if(isoperand(a[i]))
push(a[i]-'0');
else
{
x2=pop();x1=pop();
switch(a[i])
{
case '+':r=x1+x2;break;
case '-':r=x1-x2;break;
case '*':r=x1*x2;break;
case '/':r=x1/x2;break;
}
push(r);
}
}
//int p=stacktop();
return top->data;
}
void main()
{
char *postfix="35*62/+4-";
post_eval(postfix);
printf("%d ",post_eval(postfix));
}