7-2 表达式转换
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
结尾无空行
输出样例:
2 3 7 4 - * + 8 4 / +
结尾无空行
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void print() //若需要输出空格则输出
{
static int flag = 0;//static变量存放在静态存储区,只进行一次初始化
if(flag) putchar(' ');
flag++;
}
int main()
{
char str[31];//输入字符串
char stack[31];//储存运算符号的栈
int top = -1;//top为-1表示栈空
int i;
gets(str);
int len = strlen(str);
for(i=0; i<len; i++)
{
if((str[i]=='+'||str[i]=='-')&&(!i||str[i-1]=='(')||isdigit(str[i]))
{
//数字或正负号直接输出//正负号只能出现在开头或中间的(之后
print();
if(str[i]!='+') putchar(str[i]);//正号虽意味着之后的字符直接输出但正号本身不输出
while(str[i+1]=='.'||isdigit(str[i+1])) putchar(str[++i]);//小数点和数字输出
}
else //处理运算符
{
if(str[i]==')') //遇到右括号则将左括号前所有运算符全部输出
{
while(top>-1&&stack[top]!='(')
{
print();
putchar(stack[top--]);
}
if(top>-1) --top;//如果栈不空,跳过左括号
}
else //除右括号外的其他情况
{
if(top==-1)
{
stack[++top] = str[i];
continue;
}
while(top>-1&&stack[top]!='(') //栈顶操作符优先级高时不断输出栈顶操作符,当前优先级高则终止循环
{
if(str[i]=='('||((str[i]=='*'||str[i]=='/')&&(stack[top]=='+'||stack[top]=='-')))
break;
print();
printf("%c",stack[top--]);
}
stack[++top] = str[i];//当前操作符入栈
}
}
}
while(top>-1) //已处理完毕,输出栈中剩余操作符
{
print();
if(stack[top]!='(') putchar(stack[top--]);//除左括号外依次输出
else top--;//跳过左括号
}
return 0;
}