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

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

2016-08-25 14:57 302 查看


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




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



题目描述

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


输入

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


输出

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


示例输入

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



示例输出

ab*cde/-f*+



提示

 


来源

 


示例程序

 

 调用栈

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <stack>
using namespace std;

int main()
{
stack<char>s;
char ch[150];
cin >> ch;
for(int i = 0; ch[i] != '#'; i++)
{
if(ch[i] >='a' && ch[i] <= 'z')
cout << ch[i];
else
{
if(ch[i] == '(')
s.push(ch[i]);
if(ch[i] == ')')
{
while(s.top() != '(')
{
cout << s.top();
s.pop();
}
s.pop();                //左括号出栈
}
if(ch[i] == '+' || ch[i] == '-')
{
while(!s.empty() && s.top() != '(')
{
cout << s.top();
s.pop();
}
s.push(ch[i]);
}
if(ch[i] == '*' || ch[i] == '/')
{
while(!s.empty() && s.top() != '(' && (s.top() == '*' || s.top() == '/'))
{                   //当为*或者/的时候,只有在优先级低的时候才出栈
cout << s.top();
s.pop();
}
s.push(ch[i]);
}
}
}
while(!s.empty())           //栈若不空,输出其中的元素
{
cout << s.top();
s.pop();
}
cout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: