Skip to content

Instantly share code, notes, and snippets.

@surinoel
Created October 16, 2019 17:37
Show Gist options
  • Save surinoel/a3cfe105f0ce47e0bbde0b5349306d35 to your computer and use it in GitHub Desktop.
Save surinoel/a3cfe105f0ce47e0bbde0b5349306d35 to your computer and use it in GitHub Desktop.
#include <stack>
#include <string>
#include <iostream>
using namespace std;
int getPriority(char c) {
if (c == '(') return 0;
else if (c == '+' || c == '-') return 1;
else if (c == '*' || c == '/') return 2;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '+' || s[i] == '-' || s[i] == '*'
|| s[i] == '/' || s[i] == '(' || s[i] == ')') {
if (s[i] == '(') {
st.push('(');
}
else if (s[i] == ')') {
while (!st.empty() && st.top() != '(') {
cout << st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty() && getPriority(s[i]) <= getPriority(st.top())) {
cout << st.top();
st.pop();
}
st.push(s[i]);
}
}
else {
cout << s[i];
}
}
while (!st.empty()) {
cout << st.top();
st.pop();
}
cout << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment