算术表达式的转换
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
输入
输入一算术表达式,以\’#\’字符作为结束标志。(数据保证无空格,只有一组输入)
输出
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
+ab-c/def
a*b+c-d/e*f
ab*cde/-f*+
代码:
#include <bits/stdc++.h>
using namespace std;
char str[1010];
char s[1010];
char a[1010];
int cmp(char ch)
{
switch(ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default :
return 3;
}
}
void head()//前缀式
{
int top1 = 0;
int top2 = 0;
int i;
int len = strlen(str);
for(i=len-2; i>=0; i--)
{
if(str[i] >= 'a' && str[i] <= 'z')
{
s[top1++] = str[i];
}
else if(str[i] != '(')
{
if(str[i] == ')')
{
a[++top2] = str[i];
}
else
{
while(top2 && a[top2] != ')' && cmp(a[top2]) > cmp(str[i]))
{
s[top1++] = a[top2];
top2--;
}
a[++top2] = str[i];
}
}
else
{
while(a[top2]!=')')
{
s[top1++] = a[top2];
top2--;
}
top2--;
}
}
while(top2)
{
s[top1++] = a[top2];
top2--;
}
for(i=top1-1;i>=0;i--)
{
cout<<s[i];
}
cout<<endl;
}
void mid()//中缀式
{
for(int i=0; str[i] != '#'; i++)
{
if(str[i] != '(' && str[i] != ')')
{
cout<<str[i];
}
}
cout<<endl;
}
void last()//后缀式
{
int top1 = 0;
int top2 = 0;
for(int i=0; str[i] != '#'; i++)
{
if(str[i] >= 'a' && str[i] <= 'z')
{
s[top1++] = str[i];
}
else if(str[i] != ')')
{
if(str[i] == '(')
{
a[++top2] = str[i];
}
else
{
while(top2 && a[top2] != '(' && cmp(a[top2]) >= cmp(str[i]))
{
s[top1++] = a[top2];
top2--;
}
a[++top2] = str[i];
}
}
else
{
while(a[top2] != '(')
{
s[top1++] = a[top2];
top2--;
}
top2--;
}
}
while(top2)
{
s[top1++] = a[top2];
top2--;
}
for(int i=0; i<top1; i++)
{
cout<<s[i];
}
cout<<endl;
}
int main()
{
std::ios::sync_with_stdio(false);
cin>>str;
head();
mid();
last();
return 0;
}