-
Notifications
You must be signed in to change notification settings - Fork 2
/
Infix to postfix expression conversion.cpp
73 lines (63 loc) · 2.03 KB
/
Infix to postfix expression conversion.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
// Infix to postfix conversion
// Converts infix expression to postfix expression using stack
// It does not check for errors in the expression
#include <iostream>
#include <stack>
#include <cstdlib>
#include <string>
//provides precedence of operators
int prec(char opr){
if(opr == '+' || opr == '-') return 1;
else if(opr == '*' || opr == '/') return 2;
else if(opr == '^') return 3;
else return -1; //invalid operator
}
std::string infixToPostfix(const std::string& exp){
std::string postfix;
std::stack<char> stk;
for(int i=0; exp[i]; i++){
//an operand is encountered
if(exp[i]>= 'a' && exp[i]<= 'z' || exp[i]>= 'A' && exp[i]<= 'Z' ){
postfix.push_back(exp[i]);
}
else if(exp[i] == '('){
stk.push('(');
}
else if(exp[i] == ')'){
//pop out and add to postfix everything until the closing parenthesis is found
while(!stk.empty() && stk.top() != '('){
postfix.push_back(stk.top());
stk.pop();
}
if(!stk.empty()) stk.pop(); //pop the closing parenthesis
else{
//since the closing parenthesis was not found
std::cerr<<"Invalid infix expression: "<<exp<<std::endl;
exit(1);
}
}
//an operator is encountered
else{
//pop and add to postfix everything until an operator
//with greater precedence than current exp[i] is encountered
while(!exp.empty() && prec(exp[i]) <= prec(stk.top())){
postfix.push_back(stk.top());
stk.pop();
}
stk.push(exp[i]);
}
}
//add everything left in stack to the postfix exp
while(!stk.empty()){
postfix.push_back(stk.top());
stk.pop();
}
return postfix;
}
int main(void)
{
using namespace std;
string infix= "((a+t)*((b+(a+c))^(c+d)))";
cout<< infixToPostfix(infix) <<endl;
return 0;
}