数据结构实验之栈二:一般算术表达式转换成后缀式

来源:互联网 发布:手机拍电影特效软件 编辑:程序博客网 时间:2024/06/11 04:33

数据结构实验之栈二:一般算术表达式转换成后缀式

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

Input

输入一个算术表达式,以‘#’字符作为结束标志。

Output

输出该表达式转换所得到的后缀式。

Example Input

a*b+(c-d/e)*f#

Example Output

ab*cde/-f*+

Hint

#include<iostream>#include<cstdio>using namespace std;typedef struct{    char *base;    char *top;} stack;string s;void Initstack(stack &t){    t.base=new char [1010];    t.top=t.base;}int empty(stack &s){    if(s.base==s.top)        return 1;    else        return 0;}void Push(stack &t,char e){    *t.top++=e;}int Pop(stack &t,char &e){    if(t.top==t.base)        return 0;    e=*--t.top;    return 1;}char gettop(stack &t){    char e=*(t.top-1);    return e;}int main(){    stack t;    cin>>s;    Initstack(t);    int len=s.size();    for(int i=0; i<len; i++)    {        if(s[i]=='#')            break;        else if(s[i]>='a'&&s[i]<='z')            cout<<s[i];        else if(!empty(t))        {            if(s[i]=='*'||s[i]=='/')            {                char e=gettop(t);                if(e=='*'||e=='/'||e==')')                {                    char a;                    Pop(t,a);                    cout<<a;                }                Push(t,s[i]);            }            else if(s[i]=='+'||s[i]=='-')            {                char e=gettop(t);                if(e!='(')                {                    char a;                    Pop(t,a);                    cout<<a;                }                Push(t,s[i]);            }            else if(s[i]==')')            {                while(!empty(t))                {                    char a;                    Pop(t,a);                    if(a=='(')                        break;                    cout<<a;                }            }            else if(s[i]=='(')            {                Push(t,s[i]);            }        }        else            Push(t,s[i]);    }    while(!empty(t))    {        char a;        Pop(t,a);        cout<<a;    }    return 0;}


0 0