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

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

這裡的 isFull 函式只檢查容器的長度是否等於或大於 maxSize,並相應返回。isEmpty 函式檢查容器的大小是否為 0。Push 和 Pop 函式分別用於從棧中新增和移除新元素。

在本部分中,我們將向這個類中新增 PEEK 操作。棧的 Peeking 操作是指獲取陣列的頂部值。因此,我們可以按如下方式實現 peek 函式 −

peek() {
   if (isEmpty()) {
      console.log("Stack Underflow!");
      return;
   }
   return this.container[this.container.length - 1];
}

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

示例

let s = new Stack(2);
s.peek();
s.push(10);
console.log(s.peek());

輸出

這將給出輸出 −

Stack Underflow!
10

更新於: 15-6 月-2020

543 次觀看

開始你的 職業生涯

透過完成課程進行認證

開始
廣告
© . All rights reserved.