CodeVS3066 中缀转后缀 题解

来源:互联网 发布:firefox知乎 编辑:程序博客网 时间:2024/06/07 15:33

今天又做了一道题目,仍然是”栈“的应用。

解题思路:对“+-*/”四个运算符号赋予“等级”,“+-”属于一个运算级,“*/”属于一个运算级,且后者运算级高于前者。这里便运用了一个常量数组存储运算级便于查询。

const char code[]="(+-*/)";const int grade[]={0, 1, 1, 2, 2, 3};
code数组元素与grade数组角标一一对应,grade[ i ]表示code[ i ]的运算级。其中“()”用于辅助运算。在主程序中利用一个Find_grade函数对个运算符的等级进行查询。
int Find_grade(char Get){for(int i = 0; i<6; ++i) if(code[i]==Get) return grade[i];}
运用栈实现由中缀表达式到后缀表达式的转换:

预先在栈中存入一个辅助元素“(",将待转字符串存入a,从左到右对a进行扫描。

如果a[ i ]为数字,直接输出。

如果a[ i ]为“(”,直接入栈。

如果a[ i ]为")",将栈中第一个"("之前的所有依次元素弹出并输出。

如果栈顶元素运算级小于a[ i ],将a[ i ]入栈。

如果以上条件均不符合,则将栈中第一个运算级小于a[ i ]之前的所有元素依次弹出并输出,再将a[ i ]入栈。

扫描结束后,栈中可能还存有运算符,所以最后还要将栈中除辅助元素“(”外所有元素弹出并输出。

以下为程序代码。

#include <cstdio>#include <stack>using namespace std;const char code[]="(+-*/)";const int grade[]={0, 1, 1, 2, 2, 3};char a[1000000+2];stack<char>s;int Find_grade(char Get){for(int i = 0; i<6; ++i) if(code[i]==Get) return grade[i];}int main() {s.push('(');scanf("%s", 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(Find_grade(s.top())<Find_grade(a[i])) s.push(a[i]);else{while(Find_grade(s.top())>=Find_grade(a[i])) printf("%c", s.top()), s.pop();s.push(a[i]);}}while(s.top()!='(') printf("%c", s.top()), s.pop();printf("\n");return 0;}
如果有错误欢迎指出!

原创粉丝点击