实现的关键在于对各符号优先级的处理。
头文件:
/*CaptainUniverse_ 2022.3.30*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
/*CaptainUniverse_ 2022.3.30*/
子函数:
/*CaptainUniverse_ 2022.3.30*/
void InitStack(sqStack *);//初始化
void Push(sqStack *,ElemType);//入栈
void Pop(sqStack *,ElemType *);//出栈
int StackLen(sqStack);//栈元素个数
/*CaptainUniverse_ 2022.3.30*/
主函数:
/*CaptainUniverse_ 2022.3.30*/
int main()
{
sqStack s;
char c,e;
InitStack(&s);
printf("请输入中缀表达式,以#结束!\n");
scanf("%c",&c);
while(c!='#')
{
while(isdigit(c)||'.'==c)
{
printf("%c",c);
scanf("%c",&c);
if(!(isdigit(c)||'.'==c))
{
printf(" ");
}
}
if(')'==c)
{
Pop(&s,&e);
while('('!=e)
{
printf("%c ",e);
Pop(&s,&e);
}
}
else if('+'==c||'-'==c)
{
if(!StackLen(s))
{
Push(&s,c);
}
else
{
do
{
Pop(&s,&e);
if('('==e)
{
Push(&s,e);
}
else
{
printf("%c ",e);
}
}while(StackLen(s)&&'('!=e);
Push(&s,c);
}
}
else if('*'==c||'/'==c||'('==c)
{
if('*'==c||'/'==c)
{
Pop(&s,&e);
if('*'==e||'/'==e)
{
printf("%c ",e);
}
else
{
Push(&s,e);
}
}
Push(&s,c);
}
else if('#'==c)
{
break;
}
else
{
printf("输入格式错误!\n");
return -1;
}
scanf("%c",&c);
}
while(StackLen(s))
{
Pop(&s,&e);
printf("%c ",e);
}
return 0;
}
/*CaptainUniverse_ 2022.3.30*/
说明:1.中缀表达式中的数字我使用char类型实现,利用atof()函数实现string到float的转变。
2.中缀表达式中仅存在“小括号”,如遇需要多优先级的运算请嵌套使用小括号。
3.注意中缀表达式中的符号应为英文字符,否则报错!