- 四則運算中綴表達式轉換成逆波蘭表達式
中綴表達式: 1 + 5 * 3 + (6 - 2) / 2 - 4
輸入['1', '+', '5', '', '3', '+', '(', '6', '-', '2', ')', '/', '2', '-', '4']
輸出[ '1', '5', '3', '', '+', '6', '2', '-', '2', '/', '+', '4', '-' ]
function toPPN(origin) {
'use strict'
if (Object.prototype.toString.call(origin) !== '[object Array]') {
console.error('非法輸入, 請輸入格式正確的中綴表達式數組')
return []
}
let ppn = [], operator = [];
// 遍歷中綴表達式轉換成的數組
for (let i = 0; i < origin.length; i++) {
const item = origin[i]
// 校驗原始輸入的元素是否符合要求
if (isNaN(item) && (['+', '-', '*', '/', '(', ')']).indexOf(item) < 0){
console.error('中綴表達式的組成元素不符合規則, 請檢查修正')
return []
}
// 判斷該位置上的元素是否為數字
if (!isNaN(item)) {
// 如果是數字, item推入ppn
ppn.push(item)
} else if (item === '(' || operator.length === 0) {
// 如果是'('或者operator為空數組, item推入operator
operator.push(item)
} else if (item === ')') {
// 如果是')', operator從末尾彈出運算符并推入ppn直到'('
do {
ppn.push(operator.pop())
} while (operator[operator.length - 1] !== '(')
// operator彈出'('
operator.pop()
} else if (!needPop(item, operator[operator.length - 1])) {
operator.push(item)
} else {
// 比較運算符的優先級, 如果item低于operator棧頂符號優先級, operator彈出尾元素并推入到ppn
while (operator.length && needPop(item, operator[operator.length - 1])) {
ppn.push(operator.pop())
}
operator.push(item)
}
}
// 最后, 逐次彈出operator尾元素入棧到ppn
while (operator.length) {
ppn.push(operator.pop())
}
return ppn
}
function needPop(a, b) {
// b: operator的尾元素
if (b === '(') return false
if ((a === '*' || a === '/') && (b === '+' || b === '-')) return false
return true
}