将中缀表达式转换为后缀表达式

主要靠的是栈内栈外优先级的设置:

#include"iostream"
#include"stdio.h"
#include"stack"
#include"algorithm"
#include"string"
#include"ctype.h"
using namespace std;
struct node
{
    char ch;
    int isp,icp;
};
char a[100];
void f(node &d)
{
    switch(d.ch){
        case '(':d.isp=1;d.icp=6;break;
        case '*':case '/':case '%':
            d.isp=5;d.icp=4;break;
        case '+':case '-':
            d.isp=3;d.icp=2;break;
        case ')':d.isp=6;d.icp=1;break;
        case '#':d.isp=d.icp=0;break;
    default:break;
    }
}
int main()
{
    node b,t;
    stack<node>s;
    node c;c.ch='#';
    f(c);
    s.push(c);
    cin>>b.ch;
    while(!s.empty())
    {
        if(isdigit(b.ch)) {cout<<b.ch;cin>>b.ch;}
        else
        {
            f(b);
            t=s.top();
            if(b.icp>t.isp) {s.push(b);cin>>b.ch;}
            else if(b.icp<t.isp) {cout<<t.ch;s.pop();}
            else {s.pop();if(t.ch=='(') cin>>b.ch;}
        }
    }
    return 0;
}
View Code

 

posted @ 2015-04-05 10:52  Run_For_Love  阅读(252)  评论(0编辑  收藏  举报