1,遇到的是数字就直接输出
2,如果是操作符或者左括号,
I,如果是空栈,那就入栈
II,如果不是空栈,在没有遇到左括号的情况下,一直输出再弹出栈顶优先级比当前的优先级更高的,再把当前的入栈
(定义优先级:+,-最低,*,/其次,括号最高)
3,如果遇到右括号,输出弹出所有元素知道遇见左括号才停止,注意左括号不要输出
4,将栈内元素全部输出
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
string a;
stack<char>s;
int i,j;
int first(char b)
{
if(b=='+'||b=='-') return 1;
if(b=='*'||b=='/') return 2;
if(b=='(') return 3;
}
void solve();
int main()
{
while(getline(cin,a))
{
while(!s.empty()) s.pop();
solve();
}
return 0;
}
void solve()
{
for(i=0;i<a.length();i++)
{
int temp=0,fg=0;
while(a[i]>='0'&&a[i]<='9')
{
temp=temp*10+(a[i]-'0');
i++;
fg=1;
}
if(fg==1) printf("%d ",temp);
//if(a[i]=='(') s.push(a[i]);
if(a[i]==')')
{
while(s.top()!='(')
{
printf("%c ",s.top());
s.pop();
}
s.pop();
}
if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'||a[i]=='(')
{
if(!s.empty())
{
while(!s.empty()&&first(s.top())>=first(a[i])&&s.top()!='(')
{
printf("%c ",s.top());
s.pop();
}
s.push(a[i]);
}
else s.push(a[i]);
}
}
while(!s.empty()){
printf("%c ",s.top());
s.pop();
}
printf("\n");
}
本文参考以下文章的思想,代码原创
(http://blog.csdn.net/mvpsendoh/article/details/6440559)