JS栈结构实现 中缀表达式转后缀表达式

26 篇文章 0 订阅
  function Stack() {
    let items = []

    this.push = function (element) {
      items.push(element)
    }
    this.pop = function () {
      return items.pop()
    }
    this.peek = function () {
      return items[items.length - 1]
    }
    this.isEmpty = function () {
      return items.length === 0
    }
    this.size = function () {
      return items.length
    }
    this.clear = function () {
      items = []
    }
    this.print = function () {
      console.log(items.toString())
    }
  }

  // 判断优先级
  function f(str) {
    let yxj;		//优先级 
    switch (str) {
      case '*': yxj = 5; break;
      case '/': yxj = 5; break;
      case '+': yxj = 4; break;
      case '-': yxj = 4; break;
    }
    return yxj;

  }


  // 创建一个栈
  stack = new Stack()

  // 表示缓存数据区
  list = new Array()
  function getList(str) {
    for (let i = 0; i < str.length; i++) {
      // 只要是数字直接缓存区
      if (str[i] >= '0' && str[i] <= '9') {
        list.push(str[i])
      } else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
        while (true) {
          if (stack.isEmpty() || stack.peek() == '(') {
            stack.push(str[i])
            break
          } else if (f(str[i]) > f(stack.peek())) {		//当前运算符优先级大于s1栈顶运算符优先级 
            stack.push(str[i]);
            break;
          }
          else {								//小于等于 
            let cc = stack.peek();
            stack.pop();
            list.push(cc);
          }
        }
      } else {
        if (str[i] == '(') {
          stack.push(str[i]);
        } else {
          while (stack.peek() != '(') {
            let ccc = stack.peek();
            stack.pop();
            list.push(ccc);
          }
          stack.pop()
        }
      }
    }

    // 将剩下的全部追加在后面
    while (!stack.isEmpty()) {
      let cccc = stack.peek();
      list.push(cccc);
      stack.pop();
    }
  }


  getList('9+(3-1)*3+10/2')

  console.log(list)
  stack.print()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值