数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
Hint
Author
1
#include <iostream>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<deque>
#include<stack>
#include<stdio.h>
#define cmax 100003
using namespace std;
//综上出栈情况分为右括号,加减号和输入结束
int main()
{
stack<char>p;
char kk;
while(kk=getchar())
{
if((kk>='a'&&kk<='z')||(kk>='A'&&kk<='Z'))
{
cout<<kk;
}
else if(kk=='+'||kk=='-')//出现加减号时,根据优先级原则,将高优先级的符号全部出栈
{
while(!p.empty()&&((p.top()=='*')||p.top()=='/'))
{printf("%c",p.top());
p.pop();
}
p.push(kk);//之后将该符号入栈
}
else if(kk=='('||kk=='*'||kk=='/')
{
p.push(kk);
}
else if(kk==')')//当出现一个右括号时,打印出栈中除左括号外的所有符号,并清空栈
{
while(p.top()!='(')
{
cout<<p.top();
p.pop();
}
p.pop();
}
else if(kk=='#')//打印出之前入栈的所有符号
{
while(!p.empty())
{
cout<<p.top();
p.pop();
}
break;
}
}
return 0;
}
/***************************************************
User name: jk160505徐红博
Result: Accepted
Take time: 0ms
Take Memory: 160KB
Submit time: 2017-01-16 11:04:08
****************************************************/ 
京公网安备 11010502036488号