中缀转后缀

来源:互联网 发布:播放视频文件修复软件 编辑:程序博客网 时间:2024/06/06 03:57
#include<iostream>#include<stdio.h>#include<cstring>#include<stack>using namespace std;int first(char b){    if(b=='(') return 0;    else if(b=='+'||b=='-') return 1;    else if(b=='*'||b=='/') return 2;}int main(){    int k;    char a[200];    scanf("%d",&k);    getchar();    while(k--)    {        gets(a);        stack<char>s;        for(int i=0; i<strlen(a); i++)        {            if(a[i]>='0'&&a[i]<='9') printf("%c ",a[i]);            else if(a[i]=='(') s.push(a[i]);            else if(a[i]==')')            {                while(s.top()!='(')                {                    printf("%c ",s.top());                    s.pop();                }                s.pop();            }            else if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/')            {                if(!s.empty())                {                    while(!s.empty()&&first(a[i])<=first(s.top()))                    {                        printf("%c ",a[i]);                        s.pop();                    }                }                s.push(a[i]);            }        }        while(!s.empty())        {            printf("%c ",s.top());            s.pop();        }        printf("\n");    }    return 0;}

引用文章地址:

http://cc.siso.edu.cn/ds/16.html

    -


0 0