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;
}