經典白話算法之中綴表達式和後綴表達式
一、後綴表達式求值
後綴表達式也叫逆波蘭表達式,其求值過程可以用到棧來輔助存儲。
假定待求值的後綴表達式為:6 5 2 3 + 8 * + 3 + *,則其求值過程如下:
(1)遍曆表達式,遇到的數字首先放入棧中,依次讀入6 5 2 3 此時棧如下所示:
(2)接著讀到“+”,則從棧中彈出3和2,執行3+2,計算結果等於5,並將5壓入到棧中。
(3)然後讀到8(數字入棧),將其直接放入棧中。
(4)讀到“*”,彈出8和5,執行8*5,並將結果40壓入棧中。
而後過程類似,讀到“+”,將40和5彈出,將40+5的結果45壓入棧...以此類推。最後求的值288。
代碼:
- #include<iostream>
- #include<stack>
- #include<stdio.h>
- #include<string.h>
- using namespace std;
- int main(){
- string PostArray;
- int len,i,a,b;
- while(cin>>PostArray){
- stack<int> Stack;
- len = PostArray.length();
- for(i = 0;i < len;i++){
- //跳過空格
- if(PostArray[i] == ' '){
- continue;
- }
- //如果是數字則入棧
- if(PostArray[i] >= '0' && PostArray[i] <= '9'){
- Stack.push(PostArray[i] - '0');
- }
- //如果是字符則從棧讀出兩個數進行運算
- else{
- //算數a出棧
- a = Stack.top();
- Stack.pop();
- //算法b出棧
- b = Stack.top();
- Stack.pop();
- //進行運算(+ - * /)
- if(PostArray[i] == '+'){
- Stack.push(a + b);
- }
- else if(PostArray[i] == '-'){
- Stack.push(a - b);
- }
- else if(PostArray[i] == '*'){
- Stack.push(a * b);
- }
- else if(PostArray[i] == '/'){
- Stack.push(a / b);
- }
- }
- }//for
- printf("%d\n",Stack.top());
- }//while
- return 0;
- }
最後更新:2017-04-03 12:56:30