在 Javascript 中將元素推入到棧中


考慮包含少數小型幫助函式的 Javascript 中的 stack 類。

示例

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

此處 isFull 函式只是檢查容器的長度是否大於或等於 maxSize,並相應返回。isEmpty 函式檢查容器的大小是否為 0。

在本節中,準備在這個類中新增 PUSH 操作。將元素推入到棧中意味著將它們新增到陣列的頂部。使用容器陣列的末尾作為陣列的頂部,因為執行所有操作都與它有關。那麼可以實現 push 函式如下 −

示例

push(element) {
   // Check if stack is full
   if (this.isFull()) {
      console.log("Stack Overflow!");
      return;
   }
   this.container.push(element);
}

可以使用以下方法檢查此函式是否工作正常 −

示例

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

輸出

這會產生 −

[]
Stack Overflow!
[ 10, 20 ]

更新時間: 15-6 月-2020

213 瀏覽

職業生涯起步

完成課程認證

開始
廣告
© . All rights reserved.