栈->一般算术表达式转换成后缀式

来源:互联网 发布:粒子群算法的具体应用 编辑:程序博客网 时间:2024/06/10 05:04
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

Input

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

Output

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

Example Input

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

Example Output

ab*cde/-f*+


这道题在一开始学栈的时候还是比较头疼的,现在看来还是比较简单的,主要是一些操作麻烦了点,参考了百度百科里的步骤,,,

·数字时,加入后缀表达式;
·运算符:
a. 若为 '(',入栈;
b. 若为 ')',则依次把栈中的的运算符加入后缀表达式中,直到出现'(',从栈中删除'(' ;
c. 若为 除括号外的其他运算符, 当其优先级高于除'('以外的栈顶运算符时,直接入栈。否则从栈顶开始,依次弹出比当前处理的运算符优先级高和优先级相等的运算符,直到一个比它优先级低的或者遇到了一个左括号为止。
·当扫描的中缀表达式结束时,栈中的的所有运算符出栈;

这样步骤就很清楚了

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <stack>using namespace std;const int N = 100;int Push(char a, char b)   //根据运算符的优先级判断能否入栈{    if(a == '*' || a == '/')        return 0;    if(b == '*' || b == '/' || a == '(')        return 1;    return 0;}int main(){    char str[N];    stack<char> s;    scanf("%s", str);    int len = strlen(str);    for(int i = 0; i < len-1; i++)    {        if(str[i] >= 'a' && str[i] <= 'z')  //运算数直接输出到后缀式中            printf("%c", str[i]);        else        {            if(str[i] == '(')                  s.push(str[i]);            else if(str[i] == ')')            {                while(s.top() != '(')                {                    printf("%c", s.top());                    s.pop();                }                s.pop();            }            else            {                while(!s.empty() && !Push(s.top(), str[i]))                {                    printf("%c", s.top());                    s.pop();                }                    s.push(str[i]);            }        }    }    while(!s.empty())    {        printf("%c", s.top());        s.pop();    }    return 0;}


阅读全文
0 0
原创粉丝点击