JavaScript Program for Implementation of Stack using Linked List

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where elements are added and removed from the same end, known as the top of the stack. Here we’ll understand how to implement a stack data structure using a linked list and provide operations such as push, pop, peek, and isEmpty in JavaScript.

Using linked list

In this approach, we create a new stack instance using new Stack(). Data is pushed into the stack using the push() method. The push(data) method creates a new node, sets it as the new top of the stack, and increments the stack’s size. We use the pop() method to remove the top element from the stack. Then, we use the peek() method to get the top element of the stack. The isEmpty() method is used to check if the stack is empty. We have tested all of the above operations on a stack and printed the output.

Example: The example below shows the stack implementation using a linked list in JavaScript.

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

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

    push(data) {
        const newNode = new Node(data);
        newNode.next = this.top;
        this.top = newNode;
        this.size++;
    }

    peek() {
        return this.top ? this.top.data : null;
    }

    isEmpty() {
        return this.size === 0;
    }

    pop() {
        if (!this.top) return null;
        const popped = this.top;
        this.top = this.top.next;
        this.size--;
        return popped.data;
    }
}

const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.pop());
console.log(stack.peek());
console.log(stack.isEmpty());

Output
30
20
false