-
Notifications
You must be signed in to change notification settings - Fork 65
/
infixto_postfix
125 lines (120 loc) · 1.81 KB
/
infixto_postfix
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
#include<stdio.h>
#include<process.h>
#include<string.h>
char stack[20]; //character type
int top=-1;
char pop();
void push(char item);
int isoperand(char symbol);
int isoperator(char symbol);
void converttopost(char infix[20],char postfix[20]);
int prcd(char symbol);
char pop()
{
char ch;
ch=stack[top];
top--;
return ch;
}
void push(char item)
{
top++;
stack[top]=item;
}
int isoperand(char symbol)
{
if((symbol>='a'&& symbol<='z') ||
(symbol>='A' && symbol<='Z')||
(symbol>='0' && symbol<='9'))
return 1;
else
return 0;
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')': return 1;
default: return 0;
}
}
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-': return 2;
case '*':
case '/': return 4;
case '^':
case '$': return 6;
case '(':
case ')': return 1;
}
}
void converttopost(char infix[20],char postfix[20])
{
int i,j=0;
char symbol;
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperand(symbol)==1)
{
postfix[j]=symbol;
j++;
}
else if(symbol=='(')
push(symbol);
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();
}
else if(isoperator(symbol)==1)
{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else
{
while (prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}
}
else
{
printf("\n Invalid Symbol: %c ",symbol);
exit(0);
}
}
while(top!=-1)
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
int main()
{
char infix[20],postfix[20];
printf("enter the valid infix string \n");
gets(infix);
converttopost(infix,postfix);
printf("the corresponding postfix string: %c \n");
puts(postfix);
}