Quick actions

cmd+k|ctrl+k

Navigation

Languages

js 栈实现四则运算 wip

Snippet info

Language

JavaScript

Visibility

public

Author

qwas

Created

2024-05-28T09:30:33.939016Z

Updated

2024-05-28T09:30:33.939016Z

class Stack {
  constructor() {
    this.items = [];
  }
  pop() {
    return this.items.pop();
  }
  push(data) {
    this.items.push(data);
  }
  getTop() {
    return this.items.length > 0 ? this.items[this.items.length - 1] : '';
  }
  isEmpty() {
    return this.items.length == 0;
  }
}

let operatorStack = new Stack(); // 符号栈
let numStack = new Stack(); // 数字栈

function isNum(str) {
  return !['+', '-', '*', '/'].includes(str);
}

function isOperater(str) {
  return ['+', '-', '*', '/'].includes(str);
}

function isNewHeight(oldValue, newValue) {
  if (['*', '/'].includes(oldValue)) {
    return true;
  } else if (['*', '/'].includes(oldValue)) {
    return false;
  }
}

function calc(a, op, b) {
  switch (op) {
    case '+':
      return a + b;
    case '-':
      return a - b;
    case '*':
      return a * b;
    case '/':
      return a / b;
    default:
      return 0;
  }
}

// 计算 1+2*3+4-5
let arr = [1, '+', 2, '*', 3, '+', 4, '-', 5];
let i = 0;

while (arr[i]) {
  if (isNum(arr[i])) {
    numStack.push(arr[i]);
    i++;
  }

  if (isOperater(arr[i])) {
    if (!operatorStack.isEmpty()) {
      if (isNewHeight(operatorStack.getTop(), arr[i])) {
        operatorStack.push(arr[i]);
        i++;
      } else {
        let op = operatorStack.pop();
        let num2 = numStack.pop();
        let num1 = numStack.pop();

        let result = calc(num1, op, num2);
        console.log('calc1', num1, op, num2);

        numStack.push(result);
      }
    } else {
      operatorStack.push(arr[i]);
      i++;
    }
  }
}

while (operatorStack.items.length > 0) {
  let op = operatorStack.pop();

  let num2 = numStack.pop();
  let num1 = numStack.pop();

  let result = calc(num1, op, num2);
  console.log('calc2', num1, op, num2);
  numStack.push(result);
}

console.log('numStack', numStack.items);
console.log('operatorStack', operatorStack.items);
INFO