LinkedList as Stack

LinkedList as Stack

In Java, Stack is a subclass of Vector, but it can be implemented using a LinkedList for better performance in some cases. Here's a practical way to use LinkedList as a stack:

Why Use LinkedList for Stack?

  • LinkedList provides efficient addFirst() and removeFirst() methods, which can mimic stack operations efficiently.

  • Unlike Stack, which is synchronized and less performant, LinkedList offers a more lightweight alternative.

Example Code Using LinkedList as a Stack

import java.util.LinkedList;

public class LinkedListAsStack {
    public static void main(String[] args) {
        LinkedList<String> stack = new LinkedList<>();

        // Push operation (addFirst)
        stack.addFirst("A");
        stack.addFirst("B");
        stack.addFirst("C");

        System.out.println("Stack after pushes: " + stack);

        // Pop operation (removeFirst)
        System.out.println("Popped: " + stack.removeFirst());

        // Peek operation (getFirst)
        System.out.println("Peek: " + stack.getFirst());

        System.out.println("Stack after operations: " + stack);
    }
}

Key Operations Mapping

  • Push: addFirst(E element)

  • Pop: removeFirst()

  • Peek: getFirst()

This approach keeps the stack operations efficient while leveraging the flexibility of LinkedList.