概念
棧只允許在有序的線性數據集合的一端 (棧頂) 進行數據插入和移除。因而按照後進先出 (LIFO, Last In First Out) 的原理運作。
圖示
代碼
棧節點
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
棧 Class
class Stack {
constructor() {
this.top = null;
}
/**
* 壓棧
* 將數據添加至棧頂端
*/
push(element) {
const node = new Node(element);
node.next = this.top;
this.top = node;
}
/**
* 彈棧
* 將棧頂端數據移除
*/
pop() {
this.top = this.top && this.top.next;
}
/** 訪問棧頂端元素 */
peek() {
return this.top && this.top.element;
}
}
示例
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
console.log(stack); // 2 1
console.log(stack.peek()); // 2