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