將中綴表達式轉換為后綴表達式的算法思想如下:
從左往右開始掃描中綴表達式
遇到數字加入到后綴表達式
遇到運算符時:
1、若為‘(’,入棧
2、若為’)‘,把棧中的運算符依次加入后綴表達式,直到出現'(',’(‘出棧,退出該次循環
3、若除’(‘ 和 ‘)’,要入棧的運算符優先級大於等於棧頂的運算符的優先級,直接入棧,否者,棧頂運算符出棧,再次比較,直到出現優先級低的運算符,或者棧為空,退出
中綴表達式為空時,若棧不為空,棧中元素一直出棧,直到棧為空
運算符 ( *,/ +,- )
棧內優先級 1 5 3 6
棧外優先級 6 4 2 1
C++實現如下:

#include <iostream> #include <algorithm> #include <string> #include <stack> #include <map> using namespace std; int main() { string s_mid="a+b-a*((c+d)/e-f)+g"; string s_beh=""; stack<char> stk; // stack<char> stk1; map<char,int> op;//利用map來實現運算符對應其優先級 op['(']=0; op[')']=0; op['+']=1; op['-']=1; op['*']=2; op['/']=2; string::iterator it=s_mid.begin();; while(it!=s_mid.end()) { if(op.count(*it))//判斷該元素是否為運算符 { if(*it==')')//情況2 { while(stk.top()!='(') { s_beh+=stk.top(); stk.pop(); } stk.pop(); } else if(stk.empty()||*it=='('||op[*it]>op[stk.top()])//情況1、情況3 { stk.push(*it); } else if(op[*it]<=op[stk.top()])//情況3 { while(op[*it]<=op[stk.top()]&&(!stk.empty())) { s_beh+=stk.top(); stk.pop(); if(stk.empty()) break; } stk.push(*it); } } else { s_beh+=*it; } it++; // cout<<s_beh<<'\t'; 輸出每次結構 // stk1=stk; // while(!stk1.empty()) 輸出棧內情況 // { // cout<<stk1.top(); // stk1.pop(); // } // cout<<endl; if(it==s_mid.end())//當中綴表達式輸出完成,所有元素出棧 { while(!stk.empty()) { s_beh+=stk.top(); stk.pop(); } break; } } cout<<s_beh<<endl; return 0; }
python實現如下:

#-*- coding:utf-8 -*- if __name__=='__main__': s_mid='23/b+(c*d-e*f)/g' s_beh='' d={'(':0,')':0,'+':1,'-':1,'*':2,'/':2}; l=[] while(len(s_mid)): if s_mid[0] in d.keys(): if s_mid[0]==')': while True: if l[len(l)-1]=='(': break else: s_beh+=l.pop() l.pop() elif len(l)==0 or s_mid[0]=='(' or d[l[len(l)-1]]<d[s_mid[0]]: l.append(s_mid[0]) elif d[l[len(l)-1]]>=d[s_mid[0]]: while d[l[len(l) - 1]] >= d[s_mid[0]]: s_beh+=l.pop() if len(l)==0: break l.append(s_mid[0]) else: s_beh+=s_mid[0] s_mid=s_mid[1:] if len(s_mid)==0: while len(l): s_beh += l.pop() print s_beh