您的位置:首页 > 其它

栈的应用之中缀表达式转换为后缀表达式

2016-10-02 13:50 363 查看
//思路:
//1:当读到一个操作数,立即放到后缀表达式结果中。
//2:当读到一个操作符,从存储运算符的栈中弹出元素到后缀表达式结果,直到出现级别更低的运算符为止,
//最后再把此运算符推入栈,
//但有一个例外,除非遇到),否者绝不会弹出(。
//3:当读到一个(,压入栈中。
//示例:
//中缀:a + b * c + ( d * e + f ) * g
//后缀:a b c * + d e * f + g * +
#include <stdio.h>
#include <stdlib.h>
//假设输入的中缀表达式各运算符和运算数之间均存在空格,且中缀表达式合法
char temp[100];//临时存储操作符
int topt=-1;
char result[100];//存储后缀表达式结果
int topr=-1;
int isoperator(char data[])
{
if(strlen(data)!=1)
return 0;
switch(data[0])
{
case '+':
case '-':
case '*':
case '/':
case '(':
case ')':return 1;
default:return 0;
}
}
void dealtemp(char data[])
{
if(data[0]==')'){
while(temp[topt]!='('){
result[++topr]=' ';
result[++topr]=temp[topt];
topt--;
}
topt--;
}
else if(data[0]=='*'||data[0]=='/'){
while(topt!=-1&&temp[topt]!='('&&temp[topt]!='+'&&temp[topt]!='-'){
result[++topr]=' ';
result[++topr]=temp[topt];
topt--;
}
temp[++topt]=data[0];
}
else if(data[0]=='+'||data[0]=='-'){
while(topt!=-1&&temp[topt]!='('){
result[++topr]=' ';
result[++topr]=temp[topt];
topt--;
}
temp[++topt]=data[0];
}
else{
temp[++topt]=data[0];
}
}
int main()
{
//用两个栈实现转变
char data[100];//原始的中缀数据
int flag=0;//决定当前字符串前添不添加空格
while(scanf("%s",data)!=EOF){
if(isoperator(data)){//判断是不是操作符
dealtemp(data);
}
else{
if(flag)
result[++topr]=' ';
strcpy(result+topr+1,data);
topr=strlen(result)-1;
flag=1;
}

}
while(topt!=-1){
result[++topr]=' ';
result[++topr]=temp[topt--];
}
result[++topr]='\0';
puts(result);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: