-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInfix_Postfix.cpp
93 lines (77 loc) · 2.07 KB
/
Infix_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
#include <iostream>
#include <cctype>
#include <stack>
#include <string>
using namespace std;
int eval(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
int getWeight(char ch) {
switch (ch) {
case '/':
case '*': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
string infixToPostfix(const string& infix) {
stack<char> s;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char ch = infix[i];
if (isdigit(ch)) {
postfix += ch;
} else if (ch == '(') {
s.push(ch);
} else if (ch == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
s.pop();
} else {
while (!s.empty() && getWeight(s.top()) >= getWeight(ch)) {
postfix += s.top();
s.pop();
}
s.push(ch);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int evalPostfix(const string& postfix) {
stack<int> s;
for (char ch : postfix) {
if (isdigit(ch)) {
s.push(ch - '0');
} else {
int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
int result = eval(op1, op2, ch);
s.push(result);
}
}
return s.top();
}
int main() {
string infix;
cout << "Enter the infix expression: ";
cin >> infix;
cout << "Infix Expression: " << infix << endl;
string postfix = infixToPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
int result = evalPostfix(postfix);
cout << "Evaluation Result: " << result << endl;
return 0;
}