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

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.

主站蜘蛛池模板: 遵义市| 通许县| 炉霍县| 上虞市| 四会市| 中牟县| 喀喇沁旗| 襄垣县| 呼和浩特市| 项城市| 邵阳市| 察隅县| 大化| 田阳县| 赣榆县| 朝阳市| 顺义区| 揭东县| 韶山市| 淮北市| 凤山市| 禄丰县| 商洛市| 辉县市| 明水县| 高清| 正阳县| 彩票| 永丰县| 高州市| 祁连县| 昌邑市| 嘉鱼县| 杭锦后旗| 祥云县| 微博| 黑河市| 赤壁市| 怀集县| 长武县| 榆社县|