这是本人第一次写博客,望着这大片的空白,略微有些不知所措······
好了言归正传。
这次的中缀转后缀从题目描述中很容易想到要调用栈,那么具体应如何使用呢?下面我们具体分析:
首先要明确运算符号。对于本题来说,“(+-*/)”这六个符号需要分级,“(”最低,其次为“+-”,然后是“*/”,“)”最高。下面利用数组m来进行分级。
m['(']=1;
m['+']=m['-']=2;
m['*']=m['/']=3;
m[')']=4;
其次就是数字。在读入所给字符串的过程中,因为要转为后缀表达式,所以遇到数字即可输出,不是数字再进行其他操作。if(a[i]>='0' && a[i]<='9')printf("%c",a[i]);
第三就是最头痛的运算符号的输出了,但其实经过仔细分析也可以发现规律:
1.栈顶等级大于等于当前元素等级时,输出并弹出至小于,把当前元素入栈;反之直接入栈
2.左括号直接入栈
3.右括号直接输出并弹出栈顶至出现左括号,弹出左括号(不输出,右括号不操作)
下文一一对应(顺序可能不同)
if(a[i]=='('){
s.push(a[i]);
}else if(a[i]==')'){
while(s.top()!='('){
printf("%c",s.top());
s.pop();
}
s.pop();
}else if(m[a[i]]>m[s.top()]){
s.push(a[i]);
}else{
while(/*!s.empty() &&*/m[a[i]]<=m[s.top()]){
printf("%c",s.top());
s.pop();
}
s.push(a[i]);
}
最后对细节加以处理,得出完整代码。#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;
stack<char>s;
char a[1000000+2];
int m[500+2];
int main() {
m['(']=1;
m['+']=m['-']=2;
m['*']=m['/']=3;
m[')']=4;
s.push('(');
scanf("%s",a);
a[strlen(a)]=')';
for(int i=0;a[i];++i){
if(a[i]>='0' && a[i]<='9'){
printf("%c",a[i]);
}else if(a[i]=='('){
s.push(a[i]);
}else if(a[i]==')'){
while(s.top()!='('){
printf("%c",s.top());
s.pop();
}
s.pop();
}else if(m[a[i]]>m[s.top()]){
s.push(a[i]);
}else{
while(/*!s.empty() &&*/m[a[i]]<=m[s.top()]){
printf("%c",s.top());
s.pop();
}
s.push(a[i]);
}
}
printf("\n");
return 0;
}
(初写,写的不好请见谅。有错误欢迎指出。)