- Hands-On Data Structures and Algorithms with JavaScript
- Kashyap Mukkamala
- 169字
- 2021-06-30 19:12:11
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.
推薦閱讀
- ServiceNow Application Development
- Visual C++程序設(shè)計教程
- Beginning C++ Game Programming
- CMDB分步構(gòu)建指南
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計
- FreeSWITCH 1.6 Cookbook
- 移動界面(Web/App)Photoshop UI設(shè)計十全大補
- 組態(tài)軟件技術(shù)與應(yīng)用
- 圖數(shù)據(jù)庫實戰(zhàn)
- Oracle GoldenGate 12c Implementer's Guide
- jQuery技術(shù)內(nèi)幕:深入解析jQuery架構(gòu)設(shè)計與實現(xiàn)原理
- Scala Functional Programming Patterns
- Python人工智能項目實戰(zhàn)
- AngularJS Web Application Development Cookbook
- Mastering React Test:Driven Development