SP4 ONP - Transform the Expression
#include<bits/stdc++.h>
using namespace std;
int n;
//一般的中缀转后缀
//创建两个栈,一个数字栈,一个符号栈
//遇到数字直接进数字栈
//遇到运算符,比较符号栈顶优先级,如果比栈顶运算优先级高,入符号栈,否则循环弹出数字栈两个数和符号栈顶运算符,输出,直到栈顶运算符低或者栈空
//遇到左括号,直接进栈
//遇到右括号,循环弹出数字栈顶两个数和运算符栈顶,直到弹出左括号
//由于是字符串输出,省掉了数字栈,遇到数字直接输出
int check(char a,char b)//运算符优先级比较
{
if(a==b)return 0; //相等
if(a=='(')return -1;
if(a=='^')return 1;
else if(b=='^')return -1;
if(a=='*' || a=='/')
{
if(b=='*'|| b=='/' )return 0;
else if(b=='^')return -1;
else return 1;
}
else
if(a=='+' || a=='-')
{
if(b=='+'||b=='-')return 0;
else return -1;
}
}
int main()
{
cin>>n;
while(n--)
{
string s;
stack<char>st;
stack<char>num;
cin>>s;
s='('+s+')';
for(int i=0;i<s.size();i++)
{
if(s[i]>='a' && s[i]<='z')cout<<s[i];
else if(s[i]=='(')st.push(s[i]);
else if(s[i]==')')
{
while(st.empty()==false && st.top() !='(')
{
//cout<<1<<endl;
//char a=num.top();num.pop();
//char b=num.top();num.pop();
cout<<st.top();
st.pop();
}
st.pop();
}
else
{
while(st.size() && check(st.top(),s[i])>=0)
{
//cout<<st.top()<<s[i]<<check(st.top(),s[i])<<endl;
//char a=num.top();num.pop();
//char b=num.top();num.pop();
cout<<st.top();
st.pop();
}
st.push(s[i]);
}
}
printf("\n");
}
return 0;
}