您的位置:首页 > 理论基础 > 数据结构算法

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

2016-07-28 21:02 295 查看

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


 



Time Limit: 1000MS Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

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


示例输出

ab*cde/-f*+


 

今天我看了一下栈,就是算数的后缀式

后缀式主要的转换是

以下为转载内容:/*至*/

/* 将中缀表达式(a+b)转换为后缀表达式(ab+)的算法思想:

·当读到数字直接送至输出队列中  

·当读到运算符t时,  

a.将栈中所有优先级高于或等于t的运算符弹出,送到输出队列中;    

b.t进栈  

·读到左括号时总是将它压入栈中  

·读到右括号时,将靠近栈顶的第一个左括号上面的运算符全部依次弹出,送至输出队列后,再丢弃左括号。  

        运用后缀表达式进行计算的具体做法:  

·建立一个栈S  

     ·从左到右读后缀表达式,读到数字就将它转换为数值压入栈S中,读到运算符则从栈中依次弹出两个数分别到Y和X,然后以“X   运算符   Y”的形式计算机出结果,再压加栈S中  

·如果后缀表达式未读完,就重复上面过程,最后输出栈顶的数值则为结束 */

代码实现是:(这里我用的是直接用栈存储了后缀式的表达式麻烦了,也可以直接输出就可以这样更简单)

#include <stdio.h>

#include <string.h>

#include <stack>

#include <algorithm>

using namespace std;

char a[500005];

int main()

{

    int i;

    stack<char> s;

    stack<char> s1;

    stack<char> s2;

    while(!s.empty())

    {

        s.pop();

    }

    while(!s1.empty())

    {

        s1.pop();

    }

    while(!s2.empty())

    {

        s2.pop();

    }

    gets(a);

    int sum = 0;

    int len = strlen(a);

    for(i = 0;i < len; i++)

    {

        if(a[i] == '#')

            break;

        if(a[i] >= 'a'&&a[i] <= 'z')

        {

            s.push(a[i]);

        }

        else if(a[i] == '*'||a[i] == '/')

        {

            if(s1.empty())

            {

                s1.push(a[i]);

            }

            else if(a[i] == '*'||a[i] == '/')

            {

                while(s1.top() == '*'||s1.top() == '/')

                {

                    s.push(s1.top());

                    s1.pop();

                    if(s1.empty())

                        break;

                }

                s1.push(a[i]);

            }

        }

        else if(a[i] == '+'||a[i] == '-')

        {

            if(s1.empty())

            {

                s1.push(a[i]);

            }

            else

            {

                while(s1.top() != '(')

                {

                    s.push(s1.top());

                    s1.pop();

                    if(s1.empty())

                        break;

                }

                s1.push(a[i]);

            }

        }

        else if(a[i] == '(')

        {

            s1.push(a[i]);

        }

        else if(a[i] == ')')

        {

            while(s1.top() != '(')

            {

                s.push(s1.top());

                s1.pop();

            }

            s1.pop();

        }

    }

    while(!s1.empty())

    {

        s.push(s1.top());

        s1.pop();

    }

    while(!s.empty())

    {

        s2.push(s.top());

        s.pop();

    }

    while(!s2.empty())

    {

        printf("%c",s2.top());

        s2.pop();

    }

}

代码菜鸟,如有错误,请多包涵!!

欢迎点评,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: