数据结构实验之栈与队列二:一般算术表达式转换成后缀式
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample Input
a*b+(c-d/e)*f#
Sample Output
ab*cde/-f*+
Hint:
优先级问题
代码如下;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100000
int main()
{
int top = 0, i, l;
char a[N], b[N];
scanf("%s", a);
l = strlen(a);
for(i = 0; i < l; i++) // 因为#不在判断中,所以到最后#直接退出循环
{
if(a[i] >= 'a' && a[i] <= 'z') // 遇到字母直接输出
{
printf("%c", a[i]);
}
else if(a[i] == '+' || a[i] == '-') // 当碰到+或-时
{
while(1) // 如果是括号里边
{
if(top == 0 || b[top] == '(') // 栈空 或 遇到左括号直接压入栈中
{
b[++top] = a[i];
break;
}
else
{
printf("%c", b[top--]); // 弹出栈顶元素,直到左括号或栈空
}
}
}
else if(a[i] == '(') // 遇到左括号直接压入栈中
{
b[++top] = a[i];
}
else if(a[i] == ')') // 右括号
{
for(; b[top] != '('; top--) // 将左括号之前的栈中元素弹出
{
printf("%c", b[top]);
}
top--; // 删除左括号
}
else if(a[i] == '*' || a[i] == '/') // 如果遇到乘除直接压入栈中, 在上面遇到+或-或右括号时弹出
{
b[++top] = a[i];
}
}
for(; top > 0; top--) // 直到表达式最后一个也被读入,栈中仍然有运算符
{
printf("%c", b[top]);
}
printf("\n");
return 0;
}