#include<iostream>
#include<stack>
using namespace std;
int getNextToken(char ch) {
if(ch == '^')
return 3;
else if(ch == '/' || ch=='*')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return -1;
}
void infixToPostfix(string str) {
stack<char> stac;
string re;
for(int i = 0; i < str.length(); i++) {
char ch = str[i];
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9'))
re += ch;
else if(ch == '(')
stac.push('(');
else if(ch == ')') {
while(stac.top() != '(')
{
re += stac.top();
stac.pop();
}
stac.pop();
}
else {
while(!stac.empty() && getNextToken(str[i]) <= getNextToken(stac.top())) {
re += stac.top();
stac.pop();
}
stac.push(ch);
}
}
while(!stac.empty()) {
re+= stac.top();
stac.pop();
}
cout << re << endl;
}
int main() {
string expression = "1000/(10+240)";
infixToPostfix(expression);
return 0;
}
Comments
Leave a comment