forked from DSC-COEA-Ambajogai/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluating a postfix expression using stack
88 lines (84 loc) · 1.45 KB
/
evaluating a postfix expression using stack
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
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}stack;
stack *head=NULL;
int push(int);
int pop(int *);
int evalpost(char *);
int calc(int,int,char);
void printerror();
void main()
{
char poststr[20];
printf("Enter Postfix string: ");
scanf("%s",poststr);
printf("The evaluated value of %s is %d\n",poststr,evalpost(poststr));
}
int push(int val)
{
stack *top;
top = (stack*)malloc(sizeof(stack));
if(top==NULL)
return -1;
top->data=val;
top->next=head;
head=top;
return 0;
}
int pop(int *val)
{
if(head==NULL)
return -1;
*val=head->data;
head=head->next;
return 0;
}
int calc(int a, int b, char c)
{
switch(c)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
}
return 0;
}
int value(char ch)
{
int val;
printf("Enter the value of %c: ",ch);
scanf("%d",&val);
return val;
}
int evalpost(char *symbol)
{
int i=0,op1,op2;
char ch;
while((ch=symbol[i++])!='\0')
{
if(ch==' ')
continue;
if(ch>='a'&&ch<='z')
push(value(ch));
else if(ch=='+' || ch=='-' || ch=='*' || ch=='/' )
{
if(pop(&op2)||pop(&op1))
printerror();
push(calc(op1,op2,ch));
}
}
pop(&op1);
if(!pop(&op2))
printerror();
return op1;
}
void printerror()
{
printf("The given postfix is wrong\n");
exit(0);
}