-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixToPostfix.cpp
More file actions
62 lines (54 loc) · 1.42 KB
/
infixToPostfix.cpp
File metadata and controls
62 lines (54 loc) · 1.42 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
58
59
60
61
62
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char c) {
if(c == '^') return 3;
else if(c == '/' || c == '*') return 2;
else if(c == '+' || c == '-') return 1;
else return -1;
}
string infixToPostfix(string s) {
// Your code goes here
stack<char> stk;
string ans = "";
for(int i = 0; i < s.length(); i++) {
char c = s[i];
//if char is an operand
if((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) {
ans += c;
}
// if char is an ( bracket
else if(c == '(') {
stk.push('(');
}
// if char is a ) bracket
else if(c == ')') {
while(stk.top() != '(') {
ans += stk.top();
stk.pop();
}
stk.pop();
}
// else it is an operator
else {
while(!stk.empty() && prec(c) <= prec(stk.top())) {
ans += stk.top();
stk.pop();
}
stk.push(c);
}
}
while(!stk.empty()) {
ans += stk.top();
stk.pop();
}
return ans;
}
int main() {
string exp = "(p+q)*(m-n)"; // Infix expression
cout << "Infix expression: " << exp << endl;
exp = infixToPostfix(exp); // Convert the infix expression to postfix
cout << "Postfix expression: " << exp << endl;
return 0;
}