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

来源:互联网 发布:网络词背锅什么意思 编辑:程序博客网 时间:2024/05/22 07:09

由一般式求后缀式:

1.先设立一个暂时暂时存放运算符的栈;

2.若是操作数直接输出;

3(1).若是运算符,如果栈为空,当前运算符入栈;

(2)如果不为空,和栈顶元素比较,如果优先级比栈顶元素大且不是右括号,直接入栈,如果是右括号,则输出栈里面的元素直到遇到第一个左括号,并且将左括号舍弃。

(3)如果优先级小于等于栈顶元素,若栈顶元素不是左括号,则输出栈顶元素,并将当前元素入栈;如果是,直接将当前元素入栈。

4.如果遇到结束符后栈不为空,则依次输出栈顶元素直到栈空。

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

ab*cde/-f*+

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int sta[100000];int op(char c){    if(c=='+'||c=='-')        return 1;    else if(c=='*'||c=='/')        return 2;    else if(c=='(')        return 3;    else if(c==')')        return 4;}int main(){   char ch;   int top=0;   while(scanf("%c",&ch),ch!='#')   {       if(ch>='a'&&ch<='z')            printf("%c",ch);       else       {           if(top==0)            sta[++top]=ch;           else if(op(ch)<=op(sta[top]))           {               if(sta[top]!='(')               {                   printf("%c",sta[top]);                   sta[top]=ch;               }               else                    sta[++top]=ch;           }           else           {               if(ch==')')               {                   while(sta[top]!='(')                       printf("%c",sta[top--]);                    top--;               }               else                    sta[++top]=ch;           }       }   }   while(top>0)        printf("%c",sta[top--]);   printf("\n");    return 0;}

0 0
原创粉丝点击