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

来源:互联网 发布:老鼠 知乎 编辑:程序博客网 时间:2024/06/05 16:04

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

ab*cde/-f*+
#include <iostream>#include <algorithm>#include <cstdio>using namespace std;typedef struct{    char *top,*base;} _stack;void _stackinitial(_stack &s){    s.base=(char *)malloc(1000*sizeof(int));    s.top=s.base;}void push(_stack &s,char e){    *s.top++=e;}char top(_stack &s){    return *(s.top-1);}void pop(_stack &s){    s.top--;}int em(_stack &s){    if(s.base==s.top) return 1;    else return 0;}int main(){    _stack s;    _stackinitial(s);    char str[110];    int i;    scanf("%s",str);    for(i=0; str[i]!='#'; i++)    {        if(str[i]>='a'&&str[i]<='z') printf("%c",str[i]);        else if(str[i]=='(') push(s,str[i]);        else if(str[i]==')')        {            while(top(s)!='(')            {                printf("%c",top(s));                pop(s);            }            pop(s);        }        else if(str[i]=='+'||str[i]=='-')        {            while(!em(s)&&top(s)!='(')            {                printf("%c",top(s));                pop(s);            }            push(s,str[i]);        }        else if(str[i]=='*'||str[i]=='/')        {            while(!em(s)&&top(s)!='('&&(top(s)=='*'||top(s)=='/'))            {                printf("%c",top(s));                pop(s);            }            push(s,str[i]);        }    }    while(!em(s))    {        printf("%c",top(s));        pop(s);    }    printf("\n");    return 0;}


0 0
原创粉丝点击