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

在這裡,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-Jun-2020

213 次檢視

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.