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

来源:互联网 发布:mac os 软件下载 编辑:程序博客网 时间:2024/05/22 10:33

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

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

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

示例输出

ab*cde/-f*+

提示

 

来源

 

示例程序

由一般是求后缀式:

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

2.设表达式的结束符为“#”,设运算符的栈底为“#”;

3.若当前字符是操作数,进栈;

4.若当前运算符的优先数高于栈顶运算符,进栈;

5.否则退出栈顶运算符发送给后缀式;

6.括号“(”对它之前之后的运算符起隔离作用,“)”可视为自相应左括号开始的表达式的结束符。


#include <stdio.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <algorithm>#include <stack>using namespace std;int main(){    stack<int >q;    char str[110];    int i;    scanf("%s",str);    for(i=0;str[i]!='#';i++)    {        if(str[i]>='a'&&str[i]<='z')//当遇到字母的时候直接输出;            printf("%c",str[i]);        else if(str[i]=='(')//当碰到左括号直接压进栈;            q.push(str[i]);        else if(str[i]==')')//当遇到右括号的时候;        {            while(q.top()!='(')//如果栈顶不是左括号,就证明括号里面的数值没有输完,就一直输出            {                printf("%c",q.top());                q.pop();            }            q.pop();//把左括号直接删除;        }        else if(str[i]=='+'||str[i]=='-')        {            while(!q.empty()&&q.top()!='(')            {                printf("%c",q.top());                q.pop();            }            q.push(str[i]);        }        else if(str[i]=='*'||str[i]=='/')        {            while(!q.empty()&& q.top()!= '('&&(q.top()== '*'||q.top() == '/'))            {                printf("%c",q.top());                q.pop();            }            q.push(str[i]);        }    }    while(!q.empty())//当结束的时候如果栈不为空,证明栈里还有积压的数,此时输出;    {        printf("%c",q.top());        q.pop();    }    cout<<endl;    return 0;}


1 0
原创粉丝点击