Implement stack using Linked List in java

ghz 10months ago ⋅ 120 views

Here is a simple implementation of a stack using a linked list in Java:

class Node<T> {
    T data;
    Node<T> next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

public class Stack<T> {
    private Node<T> top;

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

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

    // Push an element onto the stack
    public void push(T data) {
        Node<T> newNode = new Node<>(data);
        if (isEmpty()) {
            top = newNode;
        } else {
            newNode.next = top;
            top = newNode;
        }
    }

    // Pop an element from the stack
    public T pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        T data = top.data;
        top = top.next;
        return data;
    }

    // Peek the top element of the stack without removing it
    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        return top.data;
    }

    // Print the elements of the stack
    public void printStack() {
        Node<T> temp = top;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        
        stack.push(1);
        stack.push(2);
        stack.push(3);

        System.out.println("Stack elements:");
        stack.printStack();

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

        System.out.println("Popped element: " + stack.pop());
        System.out.println("Stack elements after pop:");
        stack.printStack();
    }
}

In this implementation, the Node class represents each element of the stack, and the Stack class provides methods to manipulate the stack. The push method adds an element to the top of the stack, the pop method removes and returns the top element of the stack, the peek method returns the top element of the stack without removing it, and the printStack method prints all elements of the stack.