算术表达式的转换
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
小明在学习了数据结构之后,突然想起了以前没有解决的算术表达式转化成后缀式的问题,今天他想解决一下。
因为有了数据结构的基础小明很快就解出了这个问题,但是他突然想到怎么求出算术表达式的前缀式和中缀式呢?小明很困惑。聪明的你帮他解决吧。
Input
输入一算术表达式,以\'#\'字符作为结束标志。(数据保证无空格,只有一组输入)
Output
输出该表达式转换所得到的前缀式 中缀式 后缀式。分三行输出,顺序是前缀式 中缀式 后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
+*ab*-c/def a*b+c-d/e*f ab*cde/-f*+
Hint
Author
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char a[150];
int len, cnt;
void solve(char *n, int f)
{
memset(a,0,sizeof(a));
stack<char>st;
cnt = 0;
for(int i = 0; i < len; i++)
{
if(n[i] <= 'z' && n[i] >= 'a')//字母直接进入数组
{
a[cnt++] = n[i];
}
else if(n[i]== '(')//左括号直接进栈
st.push(n[i]);
else if(n[i] == ')')
{
while(st.top() != '(' && !st.empty())
{
a[cnt++] = st.top();//如果不是左括号就直接进数组
st.pop();
}
st.pop();
}
else if(n[i] == '+' || n[i] == '-')
{
if(f)
{
while(!st.empty() && st.top()!= '(' && (st.top()== '*'|| st.top() == '/'))//注意判空
{
a[cnt++] = st.top();
st.pop();
}
}
else
while(! st.empty() && st.top() != '(')
{
a[cnt++] = st.top();
st.pop();
}
st.push(n[i]);
}
else if(n[i] == '*' || n[i] == '/')
{
while(!st.empty() && st.top()!= '(' && (st.top()== '*'|| st.top() == '/'))//由于优先级相同,所以先让栈顶出栈,再进栈
{
a[cnt++] = st.top();
st.pop();
}
st.push(n[i]);
}
}
while(!st.empty())
{
a[cnt++] = st.top();
st.pop();
}
}
int main()
{
char st[150], sa[150];
while(cin>>st)
{
len = strlen(st) -1;
int i;
int j;
for(i = 0, j = len - 1; i < len; i++, j--)//将字符串颠倒
{
if(st[j] == '(')
sa[i] = ')';
else if(st[j] == ')')
sa[i] = '(';
else
sa[i] = st[j];
}
solve(sa,1);//前缀
for(i = cnt -1; i >= 0; i--)
{
printf("%c", a[i]);
}
printf("\n");
for(i = 0; i < len; i++)//中缀
{
if(st[i] != '(' && st[i] != ')')
printf("%c", st[i]);
}
printf("\n");
solve(st,0);//后缀
for(i = 0; i < cnt; i++)
{
printf("%c", a[i]);
}
printf("\n");
}
return 0;
}