Simple Stack implementation using LinkedList in Java

A stack implemented with a LinkedList in Java is to push and pop elements, ensuring last-in-first-out (LIFO) order. This takes advantage of the linked list’s efficient insertion and deletion at the beginning.

Solutions:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}
public class Stack {
    private Node top;

    public Stack() {
        this.top = null;
    }

    // Push an element onto the stack
    public void push(int data) {
        Node newNode = new Node(data);
        newNode.next = top;
        top = newNode;
    }

    // Pop an element from the stack
    public int pop() {
        if (top == null) {
            throw new RuntimeException("Stack is empty");
        }
        int poppedData = top.data;
        top = top.next;
        return poppedData;
    }

    // Peek at the top element of the stack
    public int peek() {
        if (top == null) {
            throw new RuntimeException("Stack is empty");
        }
        return top.data;
    }

    // Check if the stack is empty
    public boolean isEmpty() {
        return top == null;
    }

    // Print all elements in the stack
    public void printStack() {
        Node current = top;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}
public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.print("Stack: ");
        stack.printStack();

        System.out.println("Top element is: " + stack.peek());

        System.out.println("Popped element is: " + stack.pop());

        System.out.print("Stack after pop: ");
        stack.printStack();

        System.out.println("Is stack empty? " + stack.isEmpty());
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top