官术网_书友最值得收藏!

Converting infix to postfix expressions

Putting together all the code discussed above, the final code for converting the infix expression to postfix looks like the following: 

function convert(expr) {
var postfix = "";
var ops = new Stack();
var operators = {
"^": {
priority: 4,
associativity: "rtl"
},
"*": {
priority: 3,
associativity: "ltr"
},
"/": {
priority: 3,
associativity: "ltr"
},
"+": {
priority: 2,
associativity: "ltr"
},
"-": {
priority: 2,
associativity: "ltr"
}
};


expr = clean(expr.trim().replace(/\s+/g, "").split(/([\+\-\*\/\^\(\)])/));

if (!isBalanced(expr) {
return 'error';
}

expr.forEach(function(exp) {
if(!isNaN(parseFloat(exp))) {
postfix += exp + " ";
} else if(exp === "(") {
ops.push(exp);
} else if(exp === ")") {
while(ops.peek() !== "(") {
postfix += ops.pop() + " ";
}
ops.pop();
} else if("*^+-/".indexOf(exp) !== -1) {
var currOp = exp;
var prevOp = ops.peek();
while("*^+-/".indexOf(prevOp) !== -1 && ((operators[currOp].associativity === "ltr" && operators[currOp].priority <= operators[prevOp].priority) || (operators[currOp].associativity === "rtl" && operators[currOp].priority < operators[prevOp].priority)))
{
postfix += ops.pop() + " ";
prevOp = ops.peek();
}
ops.push(currOp);
}
});

while(ops.size() > 0) {
postfix += ops.pop() + " ";
}
return postfix;
}

This converts the infix operator provided into the postfix notation.

主站蜘蛛池模板: 阳山县| 沙洋县| 观塘区| 聊城市| 新干县| 鹤岗市| 济宁市| 濮阳县| 浏阳市| 克东县| 潜山县| 泰州市| 襄汾县| 额敏县| 桂林市| 惠州市| 柳河县| 洪湖市| 萨嘎县| 扶余县| 陆川县| 梓潼县| 高唐县| 额济纳旗| 常熟市| 平原县| 宝丰县| 云和县| 江都市| 抚宁县| 吐鲁番市| 靖边县| 天峨县| 常熟市| 西充县| 桑植县| 山阴县| 内丘县| 壤塘县| 赣州市| 北京市|