在 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.