中缀表达式转后缀表达式是最常遇到的问题,也很重要,所以研究一下转化的方法。
这里只讲一下用栈的方法(还有一种是表达式树)
假定有中缀表达式 4 + ( ( 5 + 1 ) ∗ 9 ) – 20 4 + ( ( 5 + 1 ) * 9 ) – 20 4+((5+1)∗9)–20,请将它转化为后缀表达式。
从左往右找,遇到数字直接输出,遇到 (直接压入栈中,因为要和 )凑一对,遇到 )开始弹出栈中元素,到遇到第二个 (或者还没有遇到第二个 (栈就已经为空时结束此次出栈。
到最后还要检查一下栈内是否还有元素,如果有,按顺序弹出即可。注意:弹出的元素不能有(和)。
最后所得的后缀表达式即为 4 4 4 5 5 5 1 1 1 + + + 9 9 9 + + + $* $ 20 20 20 − - −
M y My My C o d e Code Code
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;
char s[100];
int t;
stack<int> q;
int main()
{
scanf("%s",s);
for(int i=0;i<strlen(s);i++){
if(s[i]!=')'){
if(s[i]>='0'&&s[i]<='9'){
printf("%c ",s[i]);
continue;
}
else
q.push(s[i]);
}
else{
t=0;
while(1){
char p=q.top();
if(p=='('){
t++;
if(t==2)
break;
}
if(p!='('&&p!=')')
printf("%c ",p);
q.pop();
if(q.empty()==1)
break;
}
}
}
while(!q.empty()){
if(q.top()!='('&&q.top()!=')')
printf("%c ",q.top());
q.pop();
}
return 0;
}
//1+((2+3)*4)-5
G O T O GOTO GOTO 表达式树

本文介绍了如何使用栈的方法将中缀表达式如4+((5+1)∗9)–204+((5+1)*9)–204+((5+1)∗9)–20转换为后缀表达式,包括栈的操作原理和代码实例。
173

被折叠的 条评论
为什么被折叠?



