-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_prefix.c
116 lines (110 loc) · 2.55 KB
/
infix_to_prefix.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
// infix to prefix expression.
# include <stdio.h>
# include <string.h>
// variables are used in the function.
char opr[25],out[25],ch;
int topopr = -1,topout = -1;
// operation for the operator stack
void pushopr(char ele){
if (topopr==24)
printf("\nStack overflow.");
else{
topopr++;
opr[topopr]=ele;
}
}
char popopr(){
if (topopr!=-1){
ch=opr[topopr];
topopr--;
}
return ch;
}
char peepopr(){
if (topopr!=-1)
ch = opr[topopr];
return ch;
}
void displayopr(){
printf("\nOperator Stack...");
for (int i = 0; i<=topopr; i++)
printf("| %c",opr[i]);
}
// operation for the output stack.
void pushout(char ele){
if (topout==24)
printf("\nStack overflow.");
else{
topout++;
out[topout]=ele;
}
}
void displayout(){
int i=0;
printf("\nOutput Stack...");
for (i = 0; i<=topout; i++)
printf("| %c",out[i]);
}
// checking the priority of the operator.
int priority(char ele){
switch (ele)
{
case '^':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
}
return -1;
}
void main(){
char infix[25],ele,popele;
printf("Enter the infix expression : ");
scanf("%s",infix);
int i=strlen(infix)-1;
while (i>=0)
{
ele = infix[i];
if (ele==')'){
pushopr(ele);
}
else if (ele=='('){
while (peepopr()!=')') // pop element upto but excluding )
{
popele = popopr();
pushout(popele);
}
// deleating the left bracket.
popopr();
}
else if (ele=='^'||ele=='+'||ele=='/'||ele=='+'||ele=='-'){
if (topopr>=0){
while (priority(peepopr())>=priority(ele) && topopr!=-1)
{
popele = popopr();
// popping out the operator with lower priority
pushout(popele);
}
}
// push the element in the operator stack which has greater priority.
pushopr(ele);
}
else{
pushout(ele);
}
displayopr();
displayout();
i--;
}
if (topopr!=-1){
while (topopr!=-1)
{
popele = popopr();
pushout(popele);
}
}
printf("\nPrefix expression = %s",strrev(out));
}