【C++】中序表達式轉後續表達式(逆波蘭表達式)

文章目錄

思路

用棧暫存運算符,讀入數據則輸出,讀入運算符則判斷優先級是否輸出。

代碼

#include <iostream>
#include <stack>
using namespace std;
stack<char> stk;
int opPri(char s){
    switch(s){
    case '+':case '-':return 2;
    case '*':case '/':case '%':return 3;
    case '(':return 1;
    case ')':return 4;
    default:return 0;
    }
}
int main(){
    char s;
    while(s=getchar(),s!='\n'){
        if(!opPri(s)){
            printf("%c",s);
        }
        else if(stk.size()==0){
            stk.push(s);
        }
        else if(s==')'){
            while(s=stk.top(),stk.pop(),s!='('){
                printf("%c",s);
            }
        }
        else if(opPri(s)>opPri(stk.top())||s=='('){
            stk.push(s);
        }
        else{
            while(opPri(s)<=opPri(stk.top())){
                printf("%c",stk.top());
                stk.pop();
                if(!stk.size()) break;
            }
            stk.push(s);
        }
    }
    while(stk.size()){
        printf("%c",stk.top());
        stk.pop();
    }
    return 0;
}

測試

  • 輸入
a+b-a*((c+d)/e-f)+g
  • 輸出
ab+acd+e/f-*-g+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章