利用栈将中缀表达式转换为后缀表达式

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)














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值