-
Notifications
You must be signed in to change notification settings - Fork 0
/
Infix To Postfix.cpp
112 lines (104 loc) · 2.78 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
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
// get weight of operators as per precedence
// higher weight given to operators with higher precedence
// for non operators, return 0
int getWeight(char ch) {
switch (ch) {
case'^':
return 3;
case '/':
case '*':
return 2;
case '+':
case '-':
return 1;
default :
return 0;
}
}//getWeight()
// convert infix expression to postfix using a stack
void infix2postfix(char infix[], char postfix[], int size) {
stack<char> s;
int weight;
int i = 0;
int k = 0;
char ch;
// iterate over the infix expression
while (i < size) {
ch = infix[i];
if (ch == '(') {
// simply push the opening parenthesis
s.push(ch);
i++;
continue;
}
if (ch == ')') {
// if we see a closing parenthesis,
// pop of all the elements and append it to
// the postfix expression till we encounter
// a opening parenthesis
while (!s.empty() && s.top() != '(') {
postfix[k++] = s.top();
s.pop();
}
// pop off the opening parenthesis also
if (!s.empty()) {
s.pop();
}
i++;
continue;
}
weight = getWeight(ch);
if (weight == 0) {
// we saw an operand
// simply append it to postfix expression
postfix[k++] = ch;
}
else {
// we saw an operator
if (s.empty()) {
// simply push the operator onto stack if
// stack is empty
s.push(ch);
}
else {
// pop of all the operators from the stack and
// append it to the postfix expression till we
// see an operator with a lower precedence that
// the current operator
while (!s.empty() && s.top() != '(' &&
weight <= getWeight(s.top())) {
postfix[k++] = s.top();
s.pop();
}
// push the current operator onto stack
s.push(ch);
}
}
i++;
}
// pop of the remaining operators present in the stack
// and append it to postfix expression
while (!s.empty()) {
postfix[k++] = s.top();
s.pop();
}
postfix[k] = 0; // null terminate the postfix expression
}
// main
int main() {
char infix[1000];
int n;
cin >> n;
for(int i=0;i<n;i++){
cin >> infix;
int size = strlen(infix);
char postfix[size];
infix2postfix(infix,postfix,size);
cout << postfix << endl;
}//for
return 0;
}