從 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);
   }
}

此處,isFull 函式檢查容器的長度是否等於或大於 maxSize,並相應返回。isEmpty 函式檢查容器的長度是否為 0。Push 函式可用於將新元素新增到堆疊中。

 在此部分,我們將在此類中新增 POP 操作。從堆疊中彈出元素表示從陣列頂部移除元素。我們認為容器陣列的末端是陣列的頂部,因為我們將對它執行所有操作。因此,我們可以實現以下彈出函式 −

示例

pop() {
   // Check if empty
   if (this.isEmpty()) {
      console.log("Stack Underflow!");
      return;
   }
   this.container.pop();
}

你可以使用以下程式碼檢查此函式是否正常工作 −

示例

let s = new Stack(2);
s.display();
s.pop();
s.push(20);
s.push(30);
s.pop();
s.display();

輸出

這會產生如下輸出 −

[]
Stack Underflow!
[ 20 ]

更新於:2020 年 6 月 15 日

231 views

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.