从 JavaScript 中的堆栈中弹出元素
考虑一个 JavaScript 中的简单堆栈类。
示例
class Stack {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize; // Init an array that'll contain the stack values.
this.container = [];
}
// A method just to see the contents while we develop this class
display() {
console.log(this.container);
}
// Checking if the array is empty
isEmpty() {
return this.container.length === 0;
}
// Check if array is full
isFull() {
return this.container.length >= maxSize;
}
push(element) {
// Check if stack is full
if (this.isFull()) {
console.log("Stack Overflow!");
return;
}
this.container.push(element);
}
}这里,isFull 函数仅仅检查容器的长度是否等于或大于 maxSize,并相应返回。isEmpty 函数检查容器的大小是否为 0。Push 函数用于将新元素添加到堆栈中。
在这一部分中,我们将在这个类中添加 POP 操作。从堆栈中弹出元素意味着将它们从数组的顶部移除。我们认为容器数组的末尾是数组的顶部,因为我们将对它执行所有操作。所以我们可以如下实现 pop 函数 -
示例
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}你可以使用以下方式检查此函数是否正常运行 -
示例
let s = new Stack(2); s.display(); s.pop(); s.push(20); s.push(30); s.pop(); s.display();
输出
这将产生以下输出 -
[] Stack Underflow! [ 20 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP