我的Javascript中缀到后缀代码是破坏jsFiddle - 为什么?

时间:2013-04-17 14:27:16

标签: javascript jsfiddle

以下是代码,我在HTML部分中提到的只有<p></p>

选项 onDomready jQuery 1.9.1

var operators = '+-*/()';

Array.prototype.peek = function () {
    return this[this.length - 1];
};

function isDigit(c) {
    return !isOperator(c);
}

function isOperator(c) {
    return operators.indexOf(c) >= 0;
}

function operatorPriority(operator) {
    return operator === '*' || operator === '/' ? 1 : 0;
}

function comparePriority(a, b) {
    return operatorPriority(a) >= operatorPriority(b);
}

function toPostfix(infix) {
    var stack = [];
    stack.push('(');
    infix += ')';

    var count = 0;
    var postfix = "";

    while (stack.length > 0) {
        var c = infix.charAt(count++);
        if (isDigit(c)) {
            postfix += c;
        } else if (c === '(') {
            stack.push(c);
        } else if (isOperator(c)) {
            while (isOperator(stack.peek())) {
                if (comparePriority(stack.peek(), c)) {
                    postfix += stack.pop();
                } else {
                    break;
                }
            }
            stack.push(c);
        } else { // assumed )
            while (stack.peek() !== '(') {
                postfix += stack.pop();
            }
            stack.pop();
        }
    }
    return postfix;
}

var infix = "2+4+5";
$('p').text(toPostfix(infix));

1 个答案:

答案 0 :(得分:1)

在您的while循环中,您必须在count上添加条件:

while (stack.length > 0 && count <= infix.length) {
    ...
}