Quick actions

cmd+k|ctrl+k

Navigation

Languages

Stack with LinkedList

Snippet info

Language

JavaScript

Visibility

public

Author

kishorrathva8298

Created

2022-04-08T14:12:48.914937Z

Updated

2022-04-08T14:13:05.381943Z

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

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }

  peek() {
    return this.top;
  }
  push(value) {
    const newNode = new Node(value);
    newNode.next = this.top;
    this.top = newNode;
    if (this.length === 0) {
      this.bottom = newNode;
    }
    this.length++;
    return this;
  }
  pop() {
    if (this.length <= 1) {
      this.top = null;
      this.bottom = null;
      this.length = Math.max(this.length-1,0);
      return this;
    }
    const secondLast = this.top.next;
    delete this.top;
    this.top = secondLast || this.bottom;
    this.length--;
    return this;
  }
}

const stack = new Stack();
stack.push(10);
stack.push(12);
stack.push(11);
stack.push(14);
// stack.pop();
// stack.pop();
// stack.pop();
// stack.pop();
// stack.pop();
// stack.pop();
// stack.pop();
console.log(stack.pop());
console.log(stack.peek())
INFO