[Codewars] Infix to Postfix Converter

Infix to Postfix Converter

  • Time :
  • Space :
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

using namespace std;
int priority(char ch) {
switch (ch)
{
case '-':
case '+':
return 0;
case '*':
case '/':
return 1;
case '^':
return 2;
default:
return -1;
}
}
std::string to_postfix(std::string infix) {
infix = '(' + infix + ')';
string res = "";
vector<char> st;
for(auto ch : infix) {
if(ch == '(') st.push_back(ch);
else if(ch == ')') {
while(st.size() and st.back() != '(') {
res.push_back(st.back()); st.pop_back();
}
st.pop_back();
} else if(isdigit(ch)) {
res.push_back(ch);
} else {
while(priority(st.back()) >= priority(ch)) {
res.push_back(st.back()); st.pop_back();
}
st.push_back(ch);
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/30/PS/Codewars/infix-to-postfix-converter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.