算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含
+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char str[27];
int len;
char stack[27];
int top=0;
int index=0;
int IsNum(char c)
{
if(c>='0'&&c<='9'||c=='.')
return 1;
else
return 0;
}
int compare(char a,char b)
{
if(b==')')return 1;
if(a=='('||b=='(')return 0;
switch(b)
{
case '+':
case '-':
return 1;
case '*':
case '/':
switch(a){
case '+':
case '-':
return 0;
case '*':
case '/':
return 1;
}
}
}
int ZhengFu(char a)
{
if(a=='+'||a=='-')
return 1;
else
return 0;
}
void Mainfun()
{
int space=0;
for(index=0;index<len;index++)
{
//先判断是否为数字,为数字就输出
if(IsNum(str[index]))
{
if(space==1)
{
printf(" ");
space =0;
}
printf("%c",str[index]);
}
//+ - 这两个符号要进一步判断是否是正负号
//判断符号为+-号 并且是在第一位 或者 前一位不是数字和‘)’ 那么这个就是正负号
else if(ZhengFu(str[index])&&( (index==0) || (IsNum(str[index-1])!=1&&str[index-1]!=')') ))
{
//如果是正负号,那么符号需要输出,正号不需要输出
if(str[index]=='-')
{
if(space==1)
{
printf(" ");
space=0;
}
printf("%c",str[index]);
}
}
//如果是运算符
else
{
if(top!=0) //栈内有运算符,需要比较
{
if(str[index]==')') //如果是')',就要输出'('之前的所有运算符
{
while(top--)
{
if(stack[top]=='(')break;
else printf(" %c",stack[top]);
}
}
else
{
while(top!=0)
{
if(compare(stack[top-1],str[index])) //来比较运算符
printf(" %c",stack[--top]);
else
break;
}
stack[top++]=str[index];
}
}
else //栈为空,直接入栈
{
stack[top++]=str[index];
}
int j;
for(j=0;j<top;j++)
if(stack[j]!='(')
{
space=1;
break;
}
}
}
while(top!=0)
printf(" %c",stack[--top]);
}
int main()
{
scanf("%s",str);
len=strlen(str);
Mainfun();
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。