首页 > 代码库 > 将中缀表达式转换为后缀表达式,然后利用栈对表达式求值。

将中缀表达式转换为后缀表达式,然后利用栈对表达式求值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://www.mamicode.com/js.js"></script>
</head>
<body>
输入中缀表达式空格分隔 例如 2 + 3
<input type="text" id="input" value=""><input type="button" onclick="fun()" value="http://www.mamicode.com/计算">
    <div id="aa">

    </div>


<script>
    /*
    *
    * #Re:【js数据结构】栈解决括号不匹配问题
    *
     *一个算术表达式的后缀表达式形式如下: op1 op2 operator
     *使用两个栈,一个用来存储操作数,另外一个用来存储操作符,设计并实现一个 JavaScript 函 数,该函数可以将中缀表达式转换为后缀表达式,然后利用栈对该表达式求值。
     */


    function Stack()
    {
        this.top = 0;
        this.arr = [];
        this.push = push;
        this.pop = pop;
        this.peek = peek;
        this.clear = clear;
        this.len = len;
        this.isEmpty = isEmpty;
    }


    function push(val)
    {
      this.arr[this.top++] = val;
    }

    function pop()
    {
        return this.arr[--this.top];
    }

    function peek(){
        return this.arr[this.top-1];
    }

    function clear(){
        delete this.arr;
        this.top = 0;
        this.arr = [];
    }

    function len(){
        return this.top;
    }



    function  isEmpty() {
        if(this.len() <= 0)
            return true;
        else
            return false;
    }


    function operatorFun(result, val, operator)
    {
        switch (operator)
        {
            case "+":
                return parseInt(result) + parseInt(val);
                break;
            case "-":
                return result - val;
                break;
            case "*":
                return result * val;
                break;
            case "/":
                return result / val;
                break;
        }
    }


    var numStack = new Stack();
    var operatorStack = new Stack();

    function fun() {
        var Str = document.getElementById("input").value;
        strline = Str.split(" ");
        for(var i = 0; i<strline.length; i++)
        {
            if(i%2 == 0)
                numStack.push(strline[i])
            else
                operatorStack.push(strline[i])

        }
        var op, operator, result;

        if(numStack.len()>0)
            result = numStack.pop()
        while(numStack.len()>0 && operatorStack.len()>0)
        {
            operator = operatorStack.pop();
            op = numStack.pop();
            result = operatorFun(result, op, operator)
        }
        console.log(result)
    }

   
</script>
</body>
</html>

  展示如下:

技术分享

   顺序从右向左,无优先级顺序,图中顺序 4*5=20, 20+4=24,结果为24

将中缀表达式转换为后缀表达式,然后利用栈对表达式求值。