JavaScript中綴運算式轉為逆波蘭式(四則運算)

來源:互聯網
上載者:User

標籤:while   ==   push   逆波蘭   javascrip   foreach   return   result   fun   

實現過程:

1.首先建立兩個空數組,result用來存放結果,temp用來存放符號;再建立一個符號集ops存放+-*/符號

2.轉運算式字元為數組,開始遍曆數組

3.如果遇到運算子,直接推入結果數組

4.遇到括弧

  1)遇到‘(‘,推入暫存區

  2)遇到‘)‘,依次彈出暫存區棧頂運算子直到‘(‘,並且刪除暫存區的‘(‘

5.遇到運算子

  1)如果暫存區

    ①為空白

    ②暫存區棧頂為‘(‘

    ③當前符號的優先順序高於暫存區棧頂運算子

    這幾種情況直接推入棧內

  2)否則,將暫存區棧頂運算子彈出並推入結果區,再次進行步驟5

6.遍曆完成則將暫存區剩餘運算子依次彈出並推入結果區

function rp(str) {    var arr = str.split(‘‘);    var ops = ‘+-#*/‘.split(‘‘); // #用來分級,+-是同一級,*/同一級,兩級之間的位置差至少為2    var result = [], temp = [];    arr.forEach(function(ele, ind) {        if (ele == ‘(‘) {            temp.push(ele); // 左括弧直接推入暫存區        } else if (ele == ‘)‘) {            var flag = true;            while (flag) {                if (temp[temp.length-1] != ‘(‘) {                    result.push(temp.pop())                } else {                    temp.pop();                    flag = false;                }            }        } else if (ops.indexOf(ele) != -1) {            cb(ele, temp)            function cb(x, o) {                if (o.length == 0 || o[o.length-1] == ‘(‘ ||                     ops.indexOf(x) - ops.indexOf(o[o.length-1]) > 2) { //判斷分級                    o.push(x)                }  else {                    result.push(o.pop());                    return cb(x, o)                }            }        } else {            result.push(ele);        }    })    while (temp.length > 0) {        if(temp[temp.length-1] != ‘(‘) {            result.push(temp.pop())        } else {            temp.pop()        }    }    return result.join(‘‘);}

實現步驟是參考一個java寫的實現過程的,然而再去找沒找到那篇文章了,找到再補上。。

JavaScript中綴運算式轉為逆波蘭式(四則運算)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.