-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix_to_postfix.c
87 lines (82 loc) · 1.52 KB
/
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
76
77
78
79
80
81
82
83
84
85
86
87
#include<stdio.h>
#include<ctype.h>
#define SIZE 30
char infix[SIZE],postfix[SIZE],s[SIZE],ch,temp;
int top=-1,i=0,j=0;
void push(char ch)
{
s[++top]=ch;
}
char pop()
{
temp=s[top--];
return temp;
}
int isoperator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^'||ch=='%')
return 1;
else
return 0;
}
int precedence(char ch)
{
switch(ch)
{
case '^':return 5; break;
case '/':
case '*':return 4; break;
case '+':
case '-':return 3; break;
case '%':return 2; break;
default: return 1; break;
}
}
void main()
{
printf("\nEnter infix expression: ");
gets(infix);
while(infix[i]!='\0')
{
ch=infix[i];
if(isalpha(ch))
{
postfix[j]=ch;
j++;
}
else if(ch=='(')
{
push(ch);
}
else if(isoperator(ch)==1)
{
if(ch!='^')
{
while(precedence(s[top])>=precedence(ch))
{
postfix[j]=pop();
j++;
}
}
push(ch);
}
else if(ch==')')
{ while(s[top]!='(')
{
postfix[j]=pop();
j++;
}
temp=pop();
}
else
printf("\nWrong input");
i++;
}
while(top!=-1)
{
postfix[j]=pop();
j++;
}
printf("\n the postfix expression is:");
puts(postfix);
}