-
Notifications
You must be signed in to change notification settings - Fork 1
/
17_infix_to_postfix.c
76 lines (72 loc) · 1.05 KB
/
17_infix_to_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
66
67
68
69
70
71
72
73
74
75
#include<stdio.h>
#include<stdlib.h>
char stack[100];
int top=-1,maxsize=100;
void push(char n)
{
if(top == maxsize )
printf(" StackOverflow \n");
else
{
top++;
stack[top]=n;
}
}
char pop()
{
if(top==-1)
{
return 0;
}
else
{
top--;
return stack[top+1];
}
}
int prec(char a)
{
if(a=='+' || a=='-')
return 1;
if(a=='*' || a=='/')
return 2;
return 0;
}
int main()
{
char infix[100],postfix[100]="",temp;
int i,j,g=0,valid=1;
printf(" Enter Infix Expression : ");
scanf("%s",infix);
for(i=0;infix[i]&&valid;i++)
{
char c=infix[i];
if(c=='(')
push('(');
else if(isalnum(c))
postfix[g++]=c;
else if(c==')')
{
while((temp=pop())!='(' && temp!=0)
postfix[g++]=temp;
if(temp==0)
valid=0;
}
else if(prec(c))
{
while((temp=pop())!=0 && prec(temp)>=prec(c))
postfix[g++]=temp;
if(temp!=0)
push(temp);
push(c);
}
else
valid=0;
}
while((temp=pop())!=0)
postfix[g++]=temp;
if(valid)
printf(" Postfix Expression : %s\n",postfix);
else
printf(" Invalid Expression ");
}