// 输入
console.log(this.getExpress(['(',1,'+','(',4,'/',2,')',')','*',6,'+',12,'-','(',6,'/','MIN(volt)',')','*',3]))
// 辅助函数 计算加减乘除
function auxiliaryCount(fisNum, secNum, op){
if(fisNum==0||secNum==0) return fisNum==0? secNum: fisNum
switch (op) {
case '+':
return fisNum + secNum
case '-':
return fisNum - secNum
case '*':
return fisNum * secNum
case '/':
return fisNum / secNum
default:
break
}
},
// 表达式处理
function getExpress(rootExpress){
let opStack = [] // 操作符栈
let trStack = [] // 计算值栈
rootExpress.forEach(ch => {
if(typeof ch == 'number'){
trStack.push(ch)
} else if(ch == '('){
opStack.push(ch)
} else if(ch == ')'){
while(opStack.length != 0){ // 计算()里面表达式
let op = opStack.pop()
if(op == '(') break
let secNum = trStack.pop()
let fisNum = trStack.length!=0? trStack.pop(): 0
trStack.push(this.auxiliaryCount(fisNum, secNum, op))
}
} else if(ch == '+'||ch == '-'||ch == '*'||ch == '/'){
while (opStack.length != 0&&opStack[opStack.length -1] != '(') { // 当操作符栈不为空且不为(
let op = opStack.pop()
let secNum = trStack.pop()
let fisNum = trStack.length!=0? trStack.pop(): 0
trStack.push(this.auxiliaryCount(fisNum, secNum, op))
}
if (opStack.length == 0||opStack[opStack.length - 1]=='(')
opStack.push(ch)
}
// console.log(opStack, trStack)
})
return this.GetValue(opStack, trStack)
},
// 求最终值
function GetValue(opStack, trStack){
while (opStack.length != 0) {
let op = opStack.pop()
let secNum = trStack.pop()
let fisNum = trStack.pop()
console.log(op, secNum, fisNum)
trStack.push(this.auxiliaryCount(fisNum, secNum, op))
}
// 最后的操作数栈OPND栈顶元素值即是表达式的
return trStack[trStack.length - 1];
}
JavaScript表达式求值算法(栈操作)
于 2023-06-05 11:53:13 首次发布