-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInfixToPostFixConversion.cpp
More file actions
57 lines (52 loc) · 1.24 KB
/
InfixToPostFixConversion.cpp
File metadata and controls
57 lines (52 loc) · 1.24 KB
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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence(char op) {
if (op == '^')
return 3;
else if (op == '*' || op == '/')
return 2;
else if (op == '+' || op == '-')
return 1;
else
return 0;
}
string infixToPostfix(string infix) {
stack<char> st;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
if (c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
postfix += c;
}
else if (c == '(') {
st.push(c);
}
else if (c == ')') {
while (st.top() != '(') {
postfix += st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty() && st.top() != '(' && precedence(c) <= precedence(st.top())) {
postfix += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
postfix += st.top();
st.pop();
}
return postfix;
}
int main() {
string infix = "a+b*c-d/e^f";
string postfix = infixToPostfix(infix);
cout << postfix << '\n';
return 0;
}