zoukankan      html  css  js  c++  java
  • SDUT 2132 数据结构实验之栈与队列二:一般算术表达式转换成后缀式

     

     

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

    Time Limit: 1000 ms Memory Limit: 65536 KiB

    Problem Description

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

    Input

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

    Output

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

    Sample Input

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

    Sample Output

    ab*cde/-f*+

    提示:本题要清楚前缀式、中缀式、后缀式与算术表达式的变换关系,算术表达式转化为后缀式,主要是从前往后找,
    遇到字母就输出,遇到*/就入栈,遇到+-判断与栈顶元素的符号优先级,栈顶元素优先级大就让其出栈,自己入栈,
    如果优先级相同就入栈,遇到括号就去掉,基本方式就是这样,可以去百度查看转换规则。

    代码实现如下(g++):
    #include<bits/stdc++.h>
    
    using namespace std;
    
    void Post(char str[])
    {
        stack<char>t;
        for(int i=0; str[i]!='#'; i++)
        {
            char x=str[i];
            if(x>='a'&&x<='z')
            {
                cout<<x;
            }
            else
            {
                if(x=='('||t.empty())
                {
                    t.push(x);
                }
                else if(x==')')
                {
                    while(t.top()!='(')
                    {
                        cout<<t.top();
                        t.pop();
                    }
                    t.pop();
                }
                else if(x=='+'||x=='-')
                {
                    while(!t.empty()&&t.top()!='(')
                    {
                        cout<<t.top();
                        t.pop();
                    }
                    t.push(x);
                }
                else if(x=='*'||x=='/')
                {
                    while(!t.empty()&&t.top()!='(')
                    {
                        if(t.top()=='*'||t.top()=='/')
                        {
                            cout<<t.top();
                            t.pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                    t.push(x);
                }
            }
        }
        while(!t.empty())
        {
            cout<<t.top();
            t.pop();
        }
    }
    
    int main()
    {
        char a[10010];
        scanf("%s",a);
        Post(a);
        return 0;
    }
    
    
    /***************************************************
    Result: Accepted
    Take time: 0ms
    Take Memory: 196KB
    ****************************************************/
  • 相关阅读:
    挑战程序设计竞赛 dp
    算法导论 动态规划
    算法导论第二章
    divide conquer
    时间戳
    bootstrap 针对超小屏幕和中等屏幕设备定义的不同的类
    jQuery中的Ajax
    怎么判断一个变量是Null还是undefined
    认识Ajax
    关于apache
  • 原文地址:https://www.cnblogs.com/jkxsz2333/p/9488097.html
Copyright © 2011-2022 走看看