基础学习——自己实现一个栈
总结自《学习JavaScript数据结构与算法第3版》
队列和栈其实很像,基础理解就是一个先进先出(队列),一个后进先出(栈),所以大致思路其实也是很像的。所以注释没有栈的详细
export default class Queue {//定义一个Queue类
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
enqueue(element) {//添加一个元素
this.items[this.count] = element;
this.count++;
}
dequeue() {//移除一个元素
if (this.isEmpty()) {
return undefined;
}
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return result;
}
peek() {//查看第一个元素
if (this.isEmpty()) {
return undefined;
}
return this.items[this.lowestCount];
}
isEmpty() {//判断是否是空
return this.size() === 0;
}
clear() {//清除所有的元素
this.items = {};
this.count = 0;
this.lowestCount = 0;
}
size() {//获取现有队列长度
return this.count - this.lowestCount;
}
toString() {//读取队列所有的内容
if (this.isEmpty()) {
return '';
}
let objString = `${this.items[this.lowestCount]}`;
for (let i = this.lowestCount + 1; i < this.count; i++){
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}