前端必会算法——栈和队列

上一篇:
前端必会算法——标准快速排序

栈和队列

栈(Stack)可以理解为是一个箱子,存放东西的容器。

在这里插入图片描述
栈结构的特点:先入后出,栈相当于一个箱子,先放进去的东西被压在了下面。
在这里插入图片描述

队列(Queue)可以理解为是一个管道。

在这里插入图片描述
队列特点:先入先出

栈结构代码实现:

var arr = [];

function push(value) {
  arr.push(value);
}

function pop() {
  return arr.pop();
}

push(1);
push(2);
push(3);

console.log(arr); // [ 1, 2, 3 ]
pop(); // 拿出去一个
console.log(arr); // [ 1, 2 ]
pop(); // 再拿出去一个
console.log(arr); // [ 1 ]

封装之后:前端经常遇到的笔试题,请用代码封装一个栈结构?

function Stack() {
  this.arr = [];
  this.push = function (value) {
    this.arr.push(value);
  };
  this.pop = function () {
    return this.arr.pop();
  };
}

var stack = new Stack();

stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.arr); // [ 1, 2, 3 ]
stack.pop();
console.log(stack.arr); // [ 1, 2, 3 ]

队列代码实现:

function Queue() {
  this.arr = [];
  this.push = function (value) {
    this.arr.push(value);
  };
  this.pop = function () {
    return this.arr.shift();
  };
}

var queue = new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
console.log(queue.arr); // [ 1, 2, 3 ]
queue.pop();
console.log(queue.arr); // [ 2, 3 ] 这回是从前面拿出来的

下一篇:
前端必会算法——双向链表

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiejiezou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值