1.中缀表达式转后缀表达式计算
1.1 如何将中缀表达式转为后缀表达式
1.2代码如下
function infixToPostfix(infix) {let outputQueue = [];let operatorStack = [];let operators = {"^": {precedence: 4,rightToLeft: true},"/": {precedence: 3,rightToLeft: false},"*": {precedence: 3,rightToLeft: false},"+": {precedence: 2,rightToLeft: false},"-": {precedence: 2,rightToLeft: false}};infix = infix.replace(/\s+/g, "");for (let char of infix.split("")) {if (/\d/.test(char)) { outputQueue.push(char);}else if ("^/*+-".includes(char)) {while (operatorStack.length &&operators[char] &&operators[operatorStack[operatorStack.length - 1]] &&operators[char].precedence <= operators[operatorStack[operatorStack.length - 1]].precedence &&!operators[char].rightToLeft) {outputQueue.push(operatorStack.pop());}operatorStack.push(char);} else if (char === "(") {operatorStack.push(char);}else if (char === ")") {while (operatorStack.length && operatorStack[operatorStack.length - 1] !== "(") {outputQueue.push(operatorStack.pop());}operatorStack.pop(); }else {throw new Error(char);}}while (operatorStack.length) {outputQueue.push(operatorStack.pop());}return outputQueue.join(" ");
}
1.3 使用方式/运行结果
const s = infixToPostfix("3+4*2/(1-5)")
1.4 如果利用后缀表达式计算
const operations = {'+': (a, b) => a + b,'-': (a, b) => a - b,'*': (a, b) => a * b,'/': (a, b) => parseInt(a / b)
};function evalRPN(tokens) {const stack = [];tokens.forEach((value) => {if (value in operations) {const [b, a] = [stack.pop(), stack.pop()]; const operation = operations[value];const result = operation(a, b);stack.push(result);} else {stack.push(parseInt(value));}});return stack.pop();
}
1.5 使用并得到结果
const s = infixToPostfix("3+4*2/(1-5)")
const value = evalRPN(s.split(" "))