數據結構Javascript實現 | 棧 stack

概念

棧只允許在有序的線性數據集合的一端 (棧頂) 進行數據插入和移除。因而按照後進先出 (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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章