DSA
Stack and Queue/Implementation

Implement Stack and Queue using Arrays

Stack using Array

class Stack {
  constructor() {
    this.size = 5;
    this.s = new Array(this.size);
    this.top = -1;
  }
 
  push(val) {
    if (this.top === this.size - 1) return;
 
    this.top++;
    this.s[this.top] = val;
  }
 
  pop() {
    if (this.top === -1) return null;
 
    const poppedEl = this.s[this.top];
    this.top--;
    return poppedEl;
  }
 
  peek() {
    if (this.top === -1) return null;
 
    return this.s[this.top];
  }
}
 
// Time complexity: O(1)
// Space complexity: O(n), n = size of array (fixed space)

Queue using Array

class Queue {
  constructor() {
    this.size = 5;
    this.q = new Array(this.size);
    this.start = -1;
    this.end = -1;
    this.curSize = 0;
  }
 
  push(val) {
    if (this.curSize === this.size) return;
 
    if (this.curSize === 0) {
      this.start = 0;
      this.end = 0;
    } else {
      this.end = (this.end + 1) % this.size;
    }
 
    this.q[this.end] = val;
    this.curSize++;
  }
 
  pop() {
    if (this.curSize === 0) return null;
 
    const poppedEl = this.q[this.start];
 
    if (this.curSize === 1) {
      this.start = -1;
      this.end = -1;
    } else {
      this.start = (this.start + 1) % this.size;
    }
 
    this.curSize--;
    return poppedEl;
  }
 
  peek() {
    if (this.curSize === 0) return null;
 
    return this.q[this.start];
  }
}
 
// Time complexity: O(1)
// Space complexity: O(n), n = size of array (fixed space)

The Queue implementation above functions like a circular queue using the modulo operator (%) to wrap around when reaching the end of the array. This is evident in the push and pop operations:

  • In the push method, we use this.end = (this.end + 1) % this.size to wrap the end pointer back to the beginning when it reaches the end of the array.
  • Similarly, in the pop method, we use this.start = (this.start + 1) % this.size to advance the start pointer in a circular manner.

On this page