栈是一种遵循后进先出 (LIFO) 原则的数据结构。最后添加的元素最先被访问。这就像把书叠在一起。你最后放的书最先被拿出来。
示例:实现栈
// program to implement stack data structure
class Stack {
constructor() {
this.items = [];
}
// add element to the stack
add(element) {
return this.items.push(element);
}
// remove element from the stack
remove() {
if(this.items.length > 0) {
return this.items.pop();
}
}
// view the last element
peek() {
return this.items[this.items.length - 1];
}
// check if the stack is empty
isEmpty(){
return this.items.length == 0;
}
// the size of the stack
size(){
return this.items.length;
}
// empty the stack
clear(){
this.items = [];
}
}
let stack = new Stack();
stack.add(1);
stack.add(2);
stack.add(4);
stack.add(8);
console.log(stack.items);
stack.remove();
console.log(stack.items);
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.size());
stack.clear();
console.log(stack.items);
输出
[1, 2, 4, 8] [1, 2, 4] 4 false 3 []
在上面的程序中,创建了Stack
类来实现栈数据结构。类方法如add()
、remove()
、peek()
、isEmpty()
、size()
、clear()
都已实现。
使用new
运算符创建了一个栈对象,并通过该对象访问了各种方法。
- 这里,最初 this.items 是一个空数组。
push()
方法将一个元素添加到 this.items。pop()
方法从 this.items 中移除最后一个元素。length
属性获取 this.items 的长度。
另请阅读