# 实现栈(基于数组)
// 栈的特性是先进后出, 类似于在一个筒子里面取乒乓球
class Z {
constructor() {
this.items = []; //基于数组
}
// 进栈
push(data) {
this.items.push(data);
}
// 出栈 栈底删除
pop() {
!this.isEmpty() && this.items.pop()
}
// 判断是不是为空
isEmpty() {
return this.items.length === 0;
}
}
const z = new Z()
z.push(1)
z.push(2)
z.push(3)
console.log(z) // 1,2,3
z.pop()
console.log(z) // 1,2,
console.log(z.isEmpty()) //false
# 实现队列(基于数组)
// 队列是先进先出的数据结构,类似于我们在银行排号,排在前面的先处理
class D {
constructor() {
this.items = []
}
// 进队列
push(data) {
data && this.items.push(data)
}
// 出队列
pop() {
!this.isEmpty() && this.items.shift();
}
// 对的长度
len() {
return this.items.length
}
// 是否为空
isEmpty() {
return this.items.length === 0;
}
}
const d = new D();
d.push(1);
d.push(2);
d.push(3);
d.pop()
console.log(d) // 2,3
# 总结
栈和队列可以看做是满足特定要求的数组,适合存储连续的数据,读的效率比较高,写的效率低
← V8执行JavaScript原理 链表 →