-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpostfix.c
More file actions
135 lines (101 loc) · 1.97 KB
/
postfix.c
File metadata and controls
135 lines (101 loc) · 1.97 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int top=-1, stack[15];
void push(char x)
{
stack[++top] = x;
}
char pop()
{
return stack[top--];
}
int precedence(char c)
{
if(c == '(')
return 0;
else if(c == '+' || c == '-')
return 1;
else if(c == '*' || c == '/')
return 2;
else if(c == '^')
return 3;
}
void infixToPostfix(char infix[],char postfix[])
{
char item, x;
int i=0, j=0;
while(infix[i] != '\0')
{
item = infix[i];
if(isalnum(item))
{
postfix[j++] = item;
}
else if(item == '(')
{
push(item);
}
else if(item==')')
{
while((x = pop()) != '(')
{
postfix[j++] = x;
}
}
else
{
while(precedence(stack[top]) >= precedence(item))
{
postfix[j++] = pop();
}
push(item);
}
i++;
}
while(top != -1)
{
postfix[j++] = pop();
}
postfix[j] = '\0';
}
void postfixEvaluation(char postfix[])
{
char ch;
int a,b,i;
for(i=0; postfix[i] != '\0'; i++)
{
ch = postfix[i];
if(isdigit(ch))
{
push(ch-'0');
}
else
{
b = pop();
a = pop();
switch(ch)
{
case '+': push(a+b);
break;
case '-': push(a-b);
break;
case '*': push(a*b);
break;
case '/': push(a/b);
break;
}
}
}
printf("\n The postfix evaluation is : %d", stack[top]);
}
void main()
{
char infix[15],postfix[15];
printf("\n Enter the infix expression : ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf(" The postfix expression is : %s",postfix);
postfixEvaluation(postfix);
printf("\n");
}