#36735:


yqiu789@gmail.com (Yi Hsun Chiu)

學校 : 國立清華大學
編號 : 236688
來源 : [58.115.172.187]
最後登入時間 :
2024-08-27 13:50:49
f377. 運算式轉換 -- 資料結構 | From: [140.114.230.78] | 發表日期 : 2023-08-04 23:35

#include <bits/stdc++.h>
using namespace std;
/*----------------------------*/

int main(){
    map<char,int> mp;
    //定義各運算子優先序
    mp['+']=1;mp['-']=1;mp['*']=2;mp['/']=2;mp['(']=0; 
    string s;
    stringstream ss;
    stack <char> stk;
    while(getline(cin,s)){
        ss.clear();
        ss.str("");
        ss<<s;
        char c;
        while(ss>>c){
            if(c<='z'&&c>='a') cout<<c<<" "; //是字母直接印出
            else{
                //如果是右括號 拿出stack內元素直到左括號
                if(c==')'){ 
                    while(stk.top()!='('){
                        cout<<stk.top()<<" ";
                        stk.pop();
                    }
                    stk.pop();
                } 
                //左括號直接放入stack
                else if(c=='(') {
                    stk.push(c); 
                }        
                else{
                    if(!stk.empty()){
                        //優先序較高的運算子疊在較低的運算子上,否則從stack拿出
                        while(!stk.empty()&&mp[c]<=mp[stk.top()]){
                        cout<<stk.top()<<" ";
                        stk.pop();
                        }   
                    }
                    stk.push(c);
                }
                
            }
        }
        //印出stack內剩餘元素
        while(!stk.empty()) {
            cout<<stk.top()<<" ";
            stk.pop();
        }
        cout<<endl;
    }
}
 
ZeroJudge Forum