考虑一下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;
}
push(element) {
//检查堆栈是否已满
if (this.isFull()) {
console.log("堆栈溢出!");
return;
}
this.container.push(element);
}
pop() {
//检查是否为空
if (this.isEmpty()) {
console.log("堆栈下溢!");
return;
}
this.container.pop();
}
}在这里,isFull函数仅检查容器的长度是否等于或大于maxSize并相应地返回。 的isEmpty功能检查是否尺寸容器的是0。PUSH和POP功能用于从堆栈分别添加和删除新的元素。
在本节中,我们将在此类中添加PEEK操作。窥视堆栈意味着获得数组的最高值。所以我们可以实现如下的偷看功能-
peek() {
if (isEmpty()) {
console.log("堆栈下溢!");
return;
}
return this.container[this.container.length - 1];
}您可以使用以下命令检查此功能是否工作正常:
let s = new Stack(2); s.peek(); s.push(10); console.log(s.peek());
输出结果
这将给出输出-
堆栈下溢! 10