数据结构实验之栈二:一般算术表达式转换成后缀式
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
输入
输入一个算术表达式,以‘#’字符作为结束标志。
输出
输出该表达式转换所得到的后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
ab*cde/-f*+
提示
#include<bits/stdc++.h>
using namespace std;
char op[10000];
char s[2000];
int judge(char c)
{
if(c=='+'||c=='-')return 1;
if(c=='/'||c=='*')return 2;
if(c=='(')return 3;
else
return 4;
}
int main()
{
int n;
// while(~scanf("%d",&n))
{
// while(n--)
{
scanf("%s",s);
int top=0;
for(int i=0; s[i]!='#';)
{
if(s[i]>='a'&&s[i]<='z'||s[i]=='.')
{
while(s[i]>='a'&&s[i]<='z'||s[i]=='.')
printf("%c",s[i++]);
// printf(" ");
continue;
}
if(top==0)
{
op[++top]=s[i++];
continue;
}
if(judge(op[top])>=judge(s[i]))
{
while(judge(op[top])>=judge(s[i])&&top>0) //要用循环<span id="transmark"></span>
{
if(op[top]!='(')
printf("%c",op[top--]);
else
break;
}
op[++top]=s[i];
i++;
}
else
{
if(s[i]==')')
{
while(op[top]!='(')
printf("%c",op[top--]);
top--;
}
else
op[++top]=s[i];
i++;
}
}
while(top)
printf("%c",op[top--]);
// printf("=\n");
}
}
return 0;
}
/*1 将中缀表达式转换为后缀表达式的算法思想:
2 ·当读到数字直接送至输出队列中
3 ·当读到运算符t时,
4 a.将栈中所有优先级高于或等于t的运算符弹出,送到输出队列中;
5 b.t进栈
6 ·读到左括号时总是将它压入栈中
7 ·读到右括号时,将靠近栈顶的左括号里面的运算符全部出栈,再丢弃左括号。
*/