DSA
Stack and Queue/Implementation

Implement Stack and Queue using Linked lists

Base node structure as always:

class Node {
  constructor(val) {
    this.data = val;
    this.next = null;
  }
}

Stack using Linked list

class Stack {
  constructor() {
    this.top = null;
  }
 
  push(val) {
    const newNode = new Node(val);
 
    newNode.next = this.top;
    this.top = newNode;
  }
 
  pop() {
    if (!this.top) return null;
 
    const poppedEl = this.top.data;
    this.top = this.top.next;
    return poppedEl;
  }
 
  peek() {
    if (!this.top) return null;
 
    return this.top.data;
  }
}
 
// Each node takes O(1) space.
 
// tl;dr
// Time complexity: O(1) for all operations
// Space complexity: O(n), n = number of elements

Queue using Linked list

class Queue {
  constructor() {
    this.start = null;
    this.end = null;
  }
 
  push(val) {
    const newNode = new Node(val);
 
    if (!this.start && !this.end) {
      this.start = newNode;
      this.end = newNode;
      return;
    }
 
    this.end.next = newNode;
    this.end = newNode;
  }
 
  pop() {
    if (!this.start) return null;
 
    const poppedEl = this.start.data;
 
    if (this.start === this.end) {
      this.start = null;
      this.end = null;
    } else {
      this.start = this.start.next;
    }
 
    return poppedEl;
  }
 
  peek() {
    if (!this.start) return null;
 
    return this.start.data;
  }
}
 
// Time complexity: O(1)
// Space complexity: O(n), n = number of elements

On this page