#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence(char op) {
if(op == '^') return 3;
if(op == '*' || op == '/') return 2;
if(op == '+' || op == '-') return 1;
return -1;
}
string infixToPostfix(string s) {
stack<char> st;
string result;
for(char c : s) {
if(isalnum(c)) {
result += c;
}
else if(c == '(') {
st.push(c);
}
else if(c == ')') {
while(!st.empty() && st.top() != '(') {
result += st.top(); st.pop();
}
st.pop(); // remove '('
}
else { // operator
while(!st.empty() && precedence(c) <= precedence(st.top())) {
result += st.top(); st.pop();
}
st.push(c);
}
}
while(!st.empty()) {
result += st.top(); st.pop();
}
return result;
}
No comments:
Post a Comment