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

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

Description

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

Input

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

Output

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

Sample

Input 

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

Output 

ab*cde/-f*+
#include <stdio.h>
#include <stdlib.h>

char s[100005]; //分配栈的大小
int main()
{
    int top=0;
    char a;
    while(scanf("%c",&a))
    {
        if(a=='#')
        break;
        else if(a>='a'&&a<='z')
            printf("%c",a); //字母直接输出
        else if(a=='(')
            s[++top]=a;  //左括号直接进栈
        else if(a==')')
        {
            for(;s[top]!='(';top--)
                printf("%c",s[top]); //将括号中元素弹出栈
            top--; //将'('弹出栈
        }
        else if(a=='+'||a=='-')
        {
            while(1)
            {
                if(top==0||s[top]=='(')
                {
                    s[++top]=a;
                    break;
                }
                printf("%c",s[top--]); //若待压栈的操作符比栈顶操作符优先级高,则直接压栈,否则将栈顶元素出栈,再接着比较继续和栈顶元素的优先级.
            }
        }
        else if(a=='*'||a=='/')
        {
            while(1)
            {
                if(s[top]=='+'||s[top]=='-'||s[top]=='('||top==0)
                {
                    s[++top]=a;
                    break;
                }
                printf("%c",s[top--]); //若待压栈的操作符比栈顶操作符优先级高,则直接压栈,否则将栈顶元素出栈,再接着比较继续和栈顶元素的优先级.
            }
        }
    }
    for(;top>0;top--)
            printf("%c",s[top]); //弹出栈中剩余元素
    return 0;
}
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12655551.html