-
Notifications
You must be signed in to change notification settings - Fork 2
/
InfixToPostfix.c
121 lines (107 loc) · 1.73 KB
/
InfixToPostfix.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
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
/*Infix to postfix expression conversion*/
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define MAX 100
char st[MAX];
int top=-1;
void push(char st[],char);
char pop(char st[]);
void InfixtoPostfix(char source[],char target[]);
int getPriority(char);
int main()
{
char infix[100],postfix[100];
printf(“\n Enter any Infix Expression: ”);
scanf(“%s”,infix);
strcpy(postfix,””);
InfixtoPostfix(infix,postfix);
printf(“\n The corresponding postfix Expression is: ”);
puts(postfix);
return 0;
}
void InfixtoPostfix(char source[],char target[])
{
int i=0,j=0;
char temp;
strcpy(target,””);
while(source[i]!=’\0’)
{
if(source[i]==’(‘)
{
push(st,source[i]);
i++;
}
else if(source[i]==’)’)
{
while((top!=-1)&&(st[top]!=’(‘))
{
target[j]=pop(st);
j++;
}
if(top==-1)
{
printf(“\n incorrect Expression”);
return;
}
temp=pop(st);
i++;
}
else if(isdigit (source[i]) || isalpha(source[i]))
{
target[j]=source[i];
j++;
i++;
}
else if(source[i]==’+’ || source[i]==’_’ || source[i]==’*’ || source[i]==’/’ || source[i]==’%’)
{
while((top!=-1)&&(st[top]!=’(‘)&&(getpriority(st[top])>getpriority(source[i])))
{
target[j]=pop(st);
j++;
}
push(st,source[i]);
i++;
}
else
{
printf(“\n incorrect element in expression”);
return;
}
}
while((top!=-1)&&(st[top]!=’(’))
{
target[j]=pop(st);
j++;
}
target[j]=’\0’;
}
int getPriority(char op)
{
if(op==’/’||op==’*’||op==’%’)
return 1;
else if(op==’+’||op==’%’)
return 0;
}
void push(char st[],char val)
{
if(top==MAX-1)
printf(“\n stack overflow”);
else
{
top++;
st[top]=val;
}
}
char pop(char st[])
{
char val=’ ’;
if(top==-1)
printf(“\n stack underflow”);
else
{
val=st[top];
top--;
}
return val;
}