考虑下面的Javascript堆栈类,其中包含一些小的辅助函数。
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;
}
}在这里,isFull函数仅检查容器的长度是否等于或大于maxSize并相应地返回。 的isEmpty函数检查容器的大小为0。
在本节中,我们将在此类中添加PUSH操作。将元素推入堆栈意味着将它们添加到数组的顶部。我们将容器数组的末尾作为数组的顶部,因为我们将对其执行所有操作。所以我们可以实现如下的push函数-
push(element) {
//检查堆栈是否已满
if (this.isFull()) {
console.log("堆栈溢出!");
return;
}
this.container.push(element);
}您可以使用以下命令检查此功能是否工作正常:
let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();
输出结果
这将给出输出-
[] 堆栈溢出! [ 10, 20 ]