-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_postfix.cpp
53 lines (46 loc) · 1.32 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
#include <iostream>
#include <stack>
#include <string>
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int precedence(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 0;
}
std::string infixToPostfix(const std::string& infix) {
std::string postfix;
std::stack<char> stack;
for (char c : infix) {
if (std::isalnum(c))
postfix += c;
else if (c == '(')
stack.push(c);
else if (c == ')') {
while (!stack.empty() && stack.top() != '(') {
postfix += stack.top();
stack.pop();
}
stack.pop(); // Pop the '('
} else if (isOperator(c)) {
while (!stack.empty() && precedence(c) <= precedence(stack.top())) {
postfix += stack.top();
stack.pop();
}
stack.push(c);
}
}
while (!stack.empty()) {
postfix += stack.top();
stack.pop();
}
return postfix;
}
int main() {
std::string infix = "A+B*C-(D/E)";
std::string postfix = infixToPostfix(infix);
std::cout << "Infix: " << infix << std::endl;
std::cout << "Postfix: " << postfix << std::endl;
return 0;
}