堆栈是一种遵循后进先出(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()
已实现。
使用
这里,最初 this.items 是一个空数组。
new
运算符创建对象堆栈,并通过该对象访问各种方法。
push()
方法向 this.items 添加一个元素。
pop()
方法从 this.items 中删除最后一个元素。
length
属性给出了 this.items 的长度。