简书地址:https://www.jianshu.com/u/489662a091fd
更多算法 持续更新中…
为什么要转换
- 中序表达式:10*(8-2*1)*2-30
- 后序表达式: 10821*-230-
- 中序表达式是给人看的,可以直观的根据优先级计算出结果,但是计算机无法自动识别优先级,因此将带有计算的优先级和括号的中序表达式变成符合某文法的后序(或前序)表达式之后,计算机可以通过从左到右(或从右到左)扫描来计算结果。
中序转后续
模拟栈
class Stack {
constructor() {
this.stack = []
this.max = 0
this.opts = {
'+': 1,
'-': 1,
'*': 5,
'/': 5,
'(': 10,
')': 10
}
}
in(char) {
this.stack.push(char)
this.max = this.opts[this.stack[this.stack.length - 1]]
}
out() {
let pop = this.stack.pop()
this.max = this.opts[this.stack[this.stack.length - 1]]
return pop
}
empty() {
return !this.stack.length
}
last() {
return this.stack[this.stack.length - 1]
}
}
中序转后序的过程
- 处理表达式:
10*(8-2*1)*2-30
处理结果为["10", "*", "(", "8", "-", "2", "*", "1", ")", "*", "2", "-", "30"]
- 遍历处理过后的中序表达式
- 遇到数字直接入栈
- 遇到’(’ 直接入栈
- 遇到 ‘)’ 则持续出栈至遇到’('停止
- 如果 (栈为空 || 当前运算符优先级较高 |