-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPostfix.cpp
109 lines (90 loc) · 2.34 KB
/
InfixToPostfix.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <cstring>
#include <stack>
#include <cstdlib>
using namespace std;
string convertToPostfix (string);
int evaluatePostfix (string);
int pres (char);
int main() {
string str;
int res;
//cout<<"Enter the expression in infix (with/without) paranthesis"<<endl;
cin>>str;
str=convertToPostfix(str);
cout<<"Postfix expression is "<<endl<<str<<endl;
res=evaluatePostfix(str);
cout<<"Result is "<<res;
return 0;
}
string convertToPostfix (string str){
int len=str.length();
stack <char> s;
string post;
for(int i=0;i<len;i++){
if(str[i]=='(')
s.push('(');
else if(str[i]==')'){
while(!s.empty() and s.top()!='('){
post+=s.top();
s.pop();
}
s.pop();
}
else if(str[i]=='+' or str[i]=='-' or str[i]=='/' or str[i]=='*'){
if( s.empty()==true or s.top()=='(' or (pres(str[i]) > pres(s.top())))
s.push(str[i]);
else{
while(!s.empty() and pres(str[i]) <= pres(s.top()) and s.top()!='('){
post+=s.top();
s.pop();
}
s.push(str[i]);
}
}
else{
post+=str[i];
}
//cout<<"entered"<<endl;
}
while(!s.empty()){
post+=s.top();
//cout<<s.top()<<endl;
s.pop();
}
return post;
}
int evaluatePostfix (string str){
stack <int> s;
int op1,op2;
for(int i=0;i<str.size();i++){
if(str[i]=='+' or str[i]=='-' or str[i]=='*' or str[i]=='/'){
op2=s.top();
s.pop();
op1=s.top();
s.pop();
switch(str[i]){
case '+': s.push(op1+op2);
break;
case '-': s.push(op1-op2);
break;
case '/': s.push(op1/op2);
break;
case '*': s.push(op1*op2);
break;
}
}
else{
s.push(str[i]-'0');
}
}
return s.top();
}
int pres(char c){
switch(c){
case '+':
case '-': return 1;
case '*':
case '/': return 2;
}
}