標籤:解決 cto main code == stack 比較 ack 入棧
第一步需要將中綴運算式轉為尾碼運算式。這步的轉化可以說是本題的核心。
主要的轉化手段是利用棧,有如下幾個規則:
- 數字直接輸出
- "("直接進棧
- ")"將棧中元素出棧直到遇到"("
- 其他運算子需要和棧頂元素比較優先順序,如果棧頂元素的優先順序小於等於待操作的運算子的,則需要出棧並輸出。直到棧頂元素的優先順序大於待處理元素
- 最後需要將棧中元素清空,全部輸出
int toint(string in){ int rst; stringstream ss; ss<<in; ss>>rst; return rst;}int priority(char a){ switch(a) { case ‘*‘: return 2; case ‘/‘: return 2; case ‘+‘: return 1; case ‘-‘: return 1; case ‘(‘: return 3; case ‘)‘: return 3; }}bool isdig(char a){ if(a>=‘0‘&&a<=‘9‘) return true; else return false;}//保證每次入棧的符號的優先順序都比當前的棧頂元素要高,若此時棧頂的優先順序比入棧元素低或者等於的話,則需要出棧//知道遇到比當前需要入棧元素優先順序高的為止void midtopost(string in,vector<string>& vec){ stack<char> s; string rst=""; int i=0; while(true) { if(i>=in.length()) break; if(isdig(in[i])) { string num=""; while(isdig(in[i])) num+=in[i++]; vec.push_back(num); } else { if(s.empty()) s.push(in[i++]); else { if(in[i]==‘(‘) {s.push(in[i]);} else if(in[i]==‘)‘) { while(s.top()!=‘(‘) { string temp=""; temp+=s.top(); vec.push_back(temp); s.pop(); } s.pop(); } else { if(priority(in[i])>priority(s.top())||s.top()==‘(‘) s.push(in[i]); else { //判斷是否為空白必須寫在前面,符合短路原則 while(!s.empty()&&(priority(in[i])<=priority(s.top()))) { string temp=""; temp+=s.top(); vec.push_back(temp); s.pop(); } s.push(in[i]); } } ++i; } } } //清空棧 while(!s.empty()) { string temp=""; temp+=s.top(); vec.push_back(temp); s.pop(); }}//尾碼運算式的計算,數字進棧,符號將棧頂兩個元素出棧,運算後進棧int calc(vector<string>& vec){ stack<int> s; for(int i=0;i<vec.size();++i) { if(!vec[i].compare("*")) { int x=s.top(); s.pop(); int y=s.top(); s.pop(); s.push(x*y); } else if(!vec[i].compare("-")) { int x=s.top(); s.pop(); int y=s.top(); s.pop(); s.push(y-x); } else if(!vec[i].compare("+")) { int x=s.top(); s.pop(); int y=s.top(); s.pop(); s.push(x+y); } else if(!vec[i].compare("/")) { int x=s.top(); s.pop(); int y=s.top(); s.pop(); s.push(y/x); } else { s.push(toint(vec[i])); } } return s.top();}int main(){ string in="9+(3-1)*3+10/2"; //string s="9 3 1 - 3 * + 10 2 / +"; vector<string> vec; midtopost(in,vec); cout<<calc(vec)<<endl; return 0; }
C++ 利用棧解決運算問題