-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathinfixToPostfix.cpp
More file actions
57 lines (53 loc) · 1.54 KB
/
Copy pathinfixToPostfix.cpp
File metadata and controls
57 lines (53 loc) · 1.54 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
#include <bits/stdc++.h>
using namespace std;
int precedence(char c){
if(c=='+'||c=='-') return 1;
if(c=='*'||c=='/') return 2;
return 0;
}
vector<string> infixToPostfix(string s, unordered_map<char,int>& vars){
stack<char> st; vector<string> out;
for(char c: s){
if(isalpha(c)) out.push_back(to_string(vars[c]));
else if(isdigit(c)) out.push_back(string(1,c));
else if(c=='(') st.push(c);
else if(c==')'){
while(!st.empty() && st.top()!='('){
out.push_back(string(1,st.top())); st.pop();
}
st.pop();
}
else {
while(!st.empty() && precedence(st.top())>=precedence(c)){
out.push_back(string(1,st.top())); st.pop();
}
st.push(c);
}
}
while(!st.empty()){
out.push_back(string(1,st.top())); st.pop();
}
return out;
}
int evalPostfix(vector<string>& exp){
stack<int> st;
for(auto &t: exp){
if(isdigit(t[0])) st.push(stoi(t));
else if(t.size()>1 || isdigit(t[0])) st.push(stoi(t));
else {
int b=st.top(); st.pop();
int a=st.top(); st.pop();
if(t=="+") st.push(a+b);
else if(t=="-") st.push(a-b);
else if(t=="*") st.push(a*b);
else if(t=="/") st.push(a/b);
}
}
return st.top();
}
int main(){
unordered_map<char,int> vars={{'x',5},{'y',3}};
string expr="(x+2)*y";
auto postfix=infixToPostfix(expr,vars);
cout<<evalPostfix(postfix)<<endl;
}