-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfix to postfix.cpp
64 lines (59 loc) · 1.48 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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// Function to get the precedence of an operator
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
}
else if (op == '*' || op == '/') {
return 2;
}
else if (op == '^') {
return 3;
}
return 0;
}
// Function to convert infix expression to postfix expression
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
char c = infix[i];
if (isalnum(c)) {
postfix += c;
}
else if (c == '(') {
s.push(c);
}
else if (c == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
if (!s.empty() && s.top() == '(') {
s.pop();
}
}
else {
while (!s.empty() && precedence(c) <= precedence(s.top())) {
postfix += s.top();
s.pop();
}
s.push(c);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "a+b*c-d/e";
string postfix = infixToPostfix(infix);
cout << "Infix expression: " << infix << endl;
cout << "Postfix expression: " << postfix << endl;
return 0;
}