js实现栈

一、栈

栈是线性结构,先进后出
新添加或删除的元素保存在栈的同一端,称为栈顶,另一端称为栈底
栈被用在编程语言的编译器和内存保存变量等,在浏览器的历史记录里用到的也是栈

二、基于数组实现

用数组模拟栈,实现以下五个方法:
push: 向栈中压入一个元素
pop: 从栈中弹出一个元素
peek: 获取栈顶元素的值
isEmpty: 判断栈是否为空
size: 获取栈的长度

function Stack() {
  this.items = [];
}

Stack.prototype.push = function (element) {
  this.items.push(element);
};

Stack.prototype.pop = function () {
  return this.items.pop();
};

Stack.prototype.peek = function () {
  return this.items[this.items.length - 1];
};

Stack.prototype.isEmpty = function () {
  return this.items.length === 0;
};

Stack.prototype.size = function () {
  return this.items.length;
};

三、基于对象实现

设计一个栈,最简单的方式是通过数组,但是数组大部分的是时间复杂度是O(n),如果能直接获取元素,并且占用较少的内存空间,我们也可以使用对象来存储栈元素,下面就是用对象模拟一个栈

function Stack() {
  this.count = 0;
  this.items = {};
}

Stack.prototype.push = function (element) {
  this.items[this.count] = element;
  this.count++;
};

Stack.prototype.pop = function () {
  if (this.isEmpty()) {
    return undefined;
  }
  this.count--;
  const result = this.items[this.count];
  delete this.items[this.count];
  return result;
};

Stack.prototype.peek = function () {
  if (this.isEmpty()) {
    return undefined;
  }
  return this.items[this.count - 1];
};

Stack.prototype.isEmpty = function () {
  return this.count === 0;
};

Stack.prototype.size = function () {
  return this.count;
};

四、栈的应用-括号匹配

输入一个字符串,包括大括号、中括号、小括号,写一个函数判断字符串中括号是否匹配。解决这个问题的思路就是:遍历字符串,遇到左括号入栈,遇到右括号,弹出栈顶元素,判断是否与右括号匹配,如果不匹配,返回false,字符串遍历完,判断栈是否为空,如果不为空,仍然返回false,最后返回true,下面是代码实现

let str = "{12*25-(4*3)}";

function isValid(str) {
  let stack = [];
  for (let item of str) {
    if (item === "{" || item === "[" || item === "(") {
      stack.push(item);
    } else if (item === "}") {
      if (stack[stack.length - 1] === "{") {
        stack.pop();
      } else {
        return false;
      }
    } else if (item === "]") {
      if (stack[stack.length - 1] === "[") {
        stack.pop();
      } else {
        return false;
      }
    } else if (item === ")") {
      if (stack[stack.length - 1] === "(") {
        stack.pop();
      } else {
        return false;
      }
    }
  }
  if (stack.length) {
    return false;
  }
  return true;
}

console.log(isValid(str));
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值