Implement Stack Using Linked List - The Coding Shala

Home >> Data Structures >> Implement Stack using Linked List

 In this post, we will learn how to Implement Stack Using Linked List and will write a Java Program for the same.

Implement Stack using Linked List

We will implement Stack operations using LinkedList. If we implement using a linked list then the stack can grow and shrink dynamically but it requires extra memory because of pointers involvement.

Java Program: 

class MyStack {
    
    Node root;
    
    //linked list node
    class Node {
        int data;
        Node next;
        
        Node(int data) {
            this.data = data;
        }
    }
 
    boolean isEmpty()
    {
        return root == null;
    }
 
    void push(int x)
    {
        Node newNode = new Node(x);
        
        //if stack is empty 
        //make this as root node
        if(root == null) {
            root = newNode;
        } else {
            //add new Node at the head
            Node tmp = root;
            newNode.next = tmp;
            root = newNode;
        }
    }
 
    int pop()
    {
        int res = -1;
        
        if(root == null) {
            //empty stack;
            return -1;
        } else {
            res = root.data;
            root = root.next;
        }
        return res;
    }
 
    int peek()
    {
        if (root == null) {
            //stack underflow
            return -1;
        }
        else {
            int x = root.data;;
            return x;
        }
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala