尽管JavaScript中的数组提供了Stack的所有功能,但让我们实现自己的Stack类。我们的类将具有以下功能-
push(element):将元素推入堆栈顶部的功能。
pop():从顶部删除元素并返回它的函数。
peek():返回堆栈顶部的元素。
isFull():检查是否达到堆栈上的元素限制。
isEmpty():检查堆栈是否为空。
clear():删除所有元素。
display():显示数组的所有内容
让我们首先定义一个简单的类,该类具有一个占用堆栈最大大小的构造函数和一个辅助函数display(),当我们为该类实现其他函数时,该辅助函数将为我们提供帮助。我们还定义了另外两个函数isFull和isEmpty,以检查堆栈是否已满或为空。
isFull函数只是检查该容器的长度等于或大于MAXSIZE并返回相应。
isEmpty函数检查的尺寸容器的是0。
当我们定义其他操作时,这些将很有帮助。从现在开始,我们定义的功能将全部放入Stack类中。
class Stack {
constructor(maxSize) {
//设置默认的最大大小(如果未提供)
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
//一种在开发此类时仅查看内容的方法
display() {
console.log(this.container);
}
//检查数组是否为空
isEmpty() {
return this.container.length === 0;
}
//检查数组是否已满
isFull() {
return this.container.length >= maxSize;
}
push(element) {
//检查堆栈是否已满
if (this.isFull()) {
console.log("堆栈溢出!");
return;
}
this.container.push(element);
}
}