从 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);
}
pop() {
// Check if empty
if (this.isEmpty()) {
console.log("Stack Underflow!");
return;
}
this.container.pop();
}
}这里,isFull 函数仅检查容器的长度是否等于或大于 maxSize,并相应地返回。isEmpty 函数检查容器的大小是否为 0。Push 和 Pop 函数分别用于向栈中添加和删除新元素。
在本节中,我们将在该类中添加 PEEK 操作。窥探栈是指获取数组的顶值。于是我们可以按如下方式实现 peek 函数 −
peek() {
if (isEmpty()) {
console.log("Stack Underflow!");
return;
}
return this.container[this.container.length - 1];
}你可以使用 − 检查此函数是否工作正常
示例
let s = new Stack(2); s.peek(); s.push(10); console.log(s.peek());
输出
这将产生以下输出 −
Stack Underflow! 10
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP