DEV Community

Ivy-Walobwa
Ivy-Walobwa

Posted on

Stack: Linked List as storage

A stack is a collection in which data is added or removed in Last in First Out order (LIFO).

stack

A stack can easily be implemented using linked list. The top data element is the head where pushing and popping items happen at the head.

stack-linkedlist

Implementation

If you've read on Linked List , this would be simple to work on.
1.We'll create a node and a stack class

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

class Stack {
    constructor() {
        this.head = null;
        this.size = 0;
    }
//add methods here
}
Enter fullscreen mode Exit fullscreen mode

2.We'll add methods to our stack class to perform push, pop and peek operations

Push node to stack
Insert the element into linked list which will be the top node of Stack

    //add data to stack
    //adds on top of stack
    push(data) {
        this.head = new Node(data, this.head);
        this.size++;
    }
Enter fullscreen mode Exit fullscreen mode

pop node from stack
Return top element from the Stack and move the top pointer to the second node of Stack

//remove data on top of stack
    //returns removed data
    pop() {
        if (this.size === 0) {
            return;
        } else {
            //select top node
            let poppedNode = this.head;
            //make second data in stack top node
            this.head = this.head.next;
            //clear popped node's link
            poppedNode.next = null;
            this.size--;
            // console.log(poppedNode);
            return poppedNode.data;
        }
    }
Enter fullscreen mode Exit fullscreen mode

peek
Return the top element.

  //return head node data
    peek() {
        if (this.size === 0) {
            return;            
        } else {
            // console.log(this.head.data)
            return this.head.data; 
        }

    }
Enter fullscreen mode Exit fullscreen mode

Example test code

let stack = new Stack();
stack.push(70);
stack.push(80);
stack.push(90);
stack.pop();
stack.peek();
Enter fullscreen mode Exit fullscreen mode

In the next series, we'll implement a stack using arrays as the storage mechanism.
Happy Learning! ❤️

Top comments (0)