-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix to postfix.cpp
146 lines (136 loc) · 3.08 KB
/
infix to postfix.cpp
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include<iostream>
#include<string>
#define MAX 20
using namespace std;
char stk[20];
int top=-1;
// Push function here, inserts value in stack and increments stack top by 1
void push(char oper)
{
if(top==MAX-1)
{
cout<<"stackfull!";
}
else
{
top++;
stk[top]=oper;
}
}
// Function to remove an item from stack. It decreases top by 1
char pop()
{
char ch;
if(top==-1)
{
cout<<"stackempty!";
}
else
{
ch=stk[top];
stk[top]='\0';
top--;
return(ch);
}
return 0;
}
int priority ( char sign )
{
if(sign == '+' || sign =='-')
{
return(1);
}
if(sign == '*' || sign =='/')
{
return(2);
}
if(sign == '$')
{
return(3);
}
return 0;
}
string convert(string infix)
{
int i=0;
string postfix = "";
while(infix[i]!='\0')
{
if(infix[i]>='a' && infix[i]<='z'|| infix[i]>='A'&& infix[i]<='Z'|| infix[i]>='0' && infix[i]<='9')
{
postfix.insert(postfix.end(),infix[i]);
i++;
}
else if(infix[i]=='(' || infix[i]=='{' || infix[i]=='[')
{
push(infix[i]);
i++;
}
else if(infix[i]==')' || infix[i]=='}' || infix[i]==']')
{
if(infix[i]==')')
{
while(stk[top]!='(')
{ postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
if(infix[i]==']')
{
while(stk[top]!='[')
{
postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
if(infix[i]=='}')
{
while(stk[top]!='{')
{
postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
}
else
{
if(top==-1)
{
push(infix[i]);
i++;
}
else if( priority(infix[i]) <= priority(stk[top])) {
postfix.insert(postfix.end(),pop());
while(priority(stk[top]) == priority(infix[i])){
postfix.insert(postfix.end(),pop());
if(top < 0) {
break;
}
}
push(infix[i]);
i++;
}
else if(priority(infix[i]) > priority(stk[top])) {
push(infix[i]);
i++;
}
}
}
while(top!=-1)
{
postfix.insert(postfix.end(),pop());
}
cout<<"The converted postfix string is : "<<postfix;
return postfix;
}
int main()
{
string infix, postfix;
cout<<"\nEnter the infix expression : ";
cin>>infix;
postfix = convert(infix);
return 0;
}