Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample
Input
a*b+(c-d/e)*f#
Output
abcde/-f+
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char s[1005];
int cnt;
void push(char n)
{
s[cnt++]=n;
}
char top()
{
return s[cnt-1];
}
void pop()
{
cnt--;
}
bool Empty()
{
if(cnt==0)
return true;
else
return false;
}
int main()
{
ios::sync_with_stdio(false);
char ch;
while(cin>>ch&&ch!='#')
{
if(ch>='a'&&ch<='z')
cout<<ch;
else if(ch=='(')
push(ch);
else if(ch==')')
{
while(top()!='(')//将括号中的元素弹出
{
cout<<top();
pop();
}
pop();//将')'出栈;
}
else if(ch=='+'||ch=='-')
{
while(true)
{
if(Empty()||top()=='(')
{
push(ch);
break;
}
cout<<top();
pop();
}
}
else if(ch=='*'||ch=='/')
{
while(true)
{
if(top()=='+'||top()=='-'||top()=='('||Empty())
{
push(ch);
break;
}
cout<<top();
pop();
}
}
}
while(!Empty())
{
cout<<top();
pop();
}
return 0;
}