1. 非运算符:直接打印
  2. 运算符:
    与栈顶元素作比较,依次出栈优先级>=此运算符的元素,遇到栈顶为更低时停止;
    当前运算符入栈;

核心代码如下:

const power = {
  "+": 1,
  "-": 1,
  "*": 2,
  "/": 2,
};
function postfix(tokens) {
  // tokens为字符数组'a+b*c/d-a+f/b'.split('');
  let stack = [];
  let result = [];
  tokens.forEach((item) => {
    // 非运算符直接打印
    if ("+-*/".indexOf(item) === -1) {
      result.push(item);
    } else {
      // 如果栈顶优先级 >= 当前运算符,就出栈
      while (power[item] <= power[stack[stack.length - 1]]) {
        result.push(stack.pop());
      }
      // 运算符入栈
      stack.push(item);
    }
  });
  // 出栈剩余的所有运算符
  while (stack.length !== 0) {
    result.push(stack.pop());
  }
  return result.join("");
}