#yyds干货盘点#js实现栈和队列
精选
原创
©著作权归作者所有:来自51CTO博客作者尼羲的原创作品,请联系作者获取转载授权,否则将追究法律责任
js实现栈的方法
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
// 返回顶部元素,但是不修改
peek() {
return this.items.at(-1);
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
toString() {
if (this.isEmpty()) {
return "";
}
let objString = `${this.items[0]}`;
for (let i = 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
js实现队列的方法
class Queue {
constructor() {
this.count = 0;
this.lowestCount = 0;
this.items = {};
}
isEmpty() {
return this.count === this.lowestCount;
}
enqueue(element) {
this.items[this.count] = element;
this.count++;
}
dequeue() {
if (this.isEmpty()) {
return void 0;
}
const result = this.items[this.lowestCount];
delete this.items[this.lowestCount];
this.lowestCount++;
return result;
}