演算法之中綴運算式和尾碼運算式

來源:互聯網
上載者:User

一、尾碼運算式求值

尾碼運算式也叫逆波蘭運算式,其求值過程可以用到棧來輔助儲存。

假定待求值的尾碼運算式為: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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.