對於簡單的四則運算而言,後綴表達式可以通過使用棧(stack)快速算出結果
==================================我是分割線====================================
後綴的定義:
e.g. 2 + 3 -> 2 3 +
2 + 3 * 4 -> 2 3 4 * +
應用棧來計算後綴表達式:
e.g. 後綴表達式 6 5 2 3 + 8 * + 3 + *
遍歷: 6 push(6) stack: 6
5 push(5) stack: 6 5
2 push(2) stack: 6 5 2
3 push(3) stack: 6 5 2 3
+ pop、pop 2、 3出棧,操作 ans = 2 + 3; push(ans) stack: 6 5 5
8 push(8) stack: 6 5 5 8
* pop、pop 5、 8出棧,操作 ans = 5 * 8; push(ans) stack: 6 5 40
+ pop、pop 5、 40出棧,操作 ans = 5 + 40; push(ans) stack: 6 45
3 push(3) stack: 6 45 3
+ pop、pop 45、 3出棧,操作 ans = 45 + 3; push(ans) stack: 6 48
* pop、pop 6、 48出棧,操作 ans = 6 * 48; push(ans) stack: 288
把中綴表達式轉化成後綴表達式:
設定: 優先級 ‘(’ > ‘*’ = ‘/’ > ‘+’ = ‘-’
①讀取輸入隊列的字符,判斷是數字還是符號+-*/()
②若是數字,放到輸出隊列
③若是‘)’,則把stack中的符號一一彈出到輸出隊列,直到遇到第一個‘(’,且‘(’不用放到輸出隊列
④若是其他符號+-*/(,則把棧中元素彈出,直到發現優先級更低的符號或者‘(’為止。'('只有在遇到‘)’時才彈出
代碼實現:
1 //2016-03-16
2 //中綴轉後綴
3
4 //局限性:輸入合法、數字為0~9的范圍
5 #include <iostream>
6 #include <string>
7 #include <stack>
8
9 using namespace std;
10
11 int main() {
12 string input, output;
13 stack<char> operators;
14 while (cin >> input) {
15 if (input == "0") break;
16 output.clear();
17 for (int i = 0; i < input.size(); i++) {
18 char ch = input[i];
19 if (ch >= '0' && ch <= '9') output.push_back(ch);
20 else if (ch == '+' || ch == '-') {
21 while (!operators.empty() && (operators.top() == '*' || operators.top() == '/' || operators.top() == '-' || operators.top() == '+')) {
22 output.push_back(operators.top());
23 operators.pop();
24 }
25 operators.push(ch);
26 }
27 else if (ch == '*' || ch == '/') {
28 while (!operators.empty() && (operators.top() == '*' || operators.top() == '/')) {
29 output.push_back(operators.top());
30 operators.pop();
31 }
32 operators.push(ch);
33 }
34 else if (ch == ')') {
35 while (operators.top() != '(' && !operators.empty()) {
36 output.push_back(operators.top());
37 operators.pop();
38 }
39 operators.pop();
40 }
41 else if (ch == '(') {
42 operators.push(ch);
43 }
44 }
45 while (!operators.empty()) {
46 output.push_back(operators.top());
47 operators.pop();
48 }
49 cout << "output : " << output << endl;
50 }
51 return 0;
52 }
測試:

局限性:(不夠健壯)
①只實現了0~9的數字輸入,若是兩位以上的數字還需要做字符判斷(前一個字符是否是數字,若是,則當前字符和前一位同屬一個整數)
②沒有做最後的結果計算,因為還是字符串,如果需要,則要做字符到整型的轉換判斷。
③沒有異常檢測(假設所有輸入都合法,不合法的輸入會直接導致錯誤輸出)
一些bugs:
①stack容器內沒有clear();
②判斷條件while (!operators.empty() && (operators.top() == '*' || operators.top() == '/'))中必須先判斷!operators.empty()
否則先判斷(operators.top() == '*' || operators.top() == '/')事實上是會做top()的讀取操作,此時棧若為空,就會runtime error