#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int checkOperator(char s) {
int priority = 0;
if (s == '*' || s == '/') {
priority = 3;
} else if (s == '+' || s == '-') {
priority = 2;
} else if (s == '('){
priority = 1;
} else {
priority = -1;
}
return priority;
}
void toPostfix(string str) {
string answer;
stack<char> s;
for (int i = 0; i < str.length(); ++i) {
char ch = str[i];
switch (ch) {
case '+':
case '-':
case '*':
case '/':
while (!s.empty() && (checkOperator(ch) <= checkOperator(s.top()))){
if (s.top() == '('){
s.pop();
} else {
answer += s.top();
s.pop();
}
}
s.push(ch);
break;
case '(':
s.push(ch);
break;
case ')':
while (s.top() != '(') {
answer += s.top();
s.pop();
}
s.pop(); // '(' pop해줌
break;
default:
// alphabet
answer += ch;
break;
}
}
// 스택에 뭔가가 남아있을때: 다 빼준다
while (!s.empty()){
if (s.top() == '('){
s.pop();
} else {
answer += s.top();
s.pop();
}
}
cout << answer << endl;
}
int main(){
string input;
cin >> input;
toPostfix(input);
return 0;
}
최근에 코딩 테스트를 봤다가 충격먹고...
기초부터 다시 해보기로 결심하고 스택을 풀었다...
자괴감 max
백준 사이트는 그냥 c++로 푸는게 마음 편할 것 같다.
후위 표기식 변환에서 가장 중요한 점을 꼽자면,
이 정도인 것 같다.