jQuery火箭图标返回顶部代码

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
****************************************************/

 

posted @ 2018-08-16 16:26  孑丶然  阅读(218)  评论(0编辑  收藏  举报
Live2D