In this tutorial, we will see Java program to implement a stack using a linked list

class Stack {
    static class Node {
        int data;
        Node next;

        Node(int d) {
            data = d;
            next = null;
        }
    }

    Node top;

    public void push(int data) {
        Node newNode = new Node(data);

        if (top == null) {
            top = newNode;
        } else {
            newNode.next = top;
            top = newNode;
        }
    }

    public int pop() {
        if (top == null) {
            // Stack underflow error
            throw new RuntimeException("Stack is empty");
        }

        int data = top.data;
        top = top.next;

        return data;
    }

    public int peek() {
        if (top == null) {
            // Stack is empty
            throw new RuntimeException("Stack is empty");
        }

        return top.data;
    }

    public boolean isEmpty() {
        return top == null;
    }
}

The Stack class defines a Node inner class that represents a node in the linked list, and a top instance variable that represents the top of the stack. The class also defines four methods: push, pop, peek, and isEmpty.

The push method takes an integer data as input and adds it to the top of the stack. The method creates a new Node with the given data and sets its next pointer to the current top of the stack. It then sets the top variable to the new Node.

The pop method removes and returns the element at the top of the stack. The method first checks if the stack is empty by checking if top is null. If the stack is not empty, the method saves the data of the current top of the stack, sets the top variable to the next element in the stack, and returns the saved data.

The peek method returns the element at the top of the stack without removing it. The method first checks if the stack is empty by checking if top is null. If the stack is not empty, the method returns the data of the current top of the stack.

The isEmpty method returns true if the stack is empty, or false otherwise. The method checks if top is null and returns the appropriate boolean value.

Thanks for Reading..