Implement a Stack

A Stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It supports two primary operations: push (add to top) and pop (remove from top). It can be implemented using a LinkedList.

General points of the algorithm:

  1. Implement the push() method to add an element to the top of the stack. Store the last previous element (tail) in the “prev” property of the new tail.
  2. Implement the pop() method: retrieve the tail node and reassign the tail to the previous element.
  3. Time complexity: O(1) for the push() and pop() methods.
  4. Space complexity: O(1) for the push() and pop() methods.
public class ImplementStack {

  private static class Stack<T> {

    private Node<T> tail;

    private static class Node<T> {

      private final T value;
      private Node<T> prev;

      public Node(T value, Node<T> prev) {
        this.value = value;
        this.prev = prev;
      }
    }

    public void push(T value) {
      var node = new Node<>(value, null);
      if (tail != null) {
        node.prev = this.tail;
      }
      this.tail = node;
    }

    public T pop() {
      if (this.tail == null) {
        throw new IllegalArgumentException("The stack is empty");
      }
      var node = this.tail;
      this.tail = this.tail.prev;
      return node.value;
    }
  }

  public static void main(String[] args) {
    var stack = new Stack<Integer>();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
    System.out.println(stack.pop());
  }
}

1 thought on “Implement a Stack”

  1. Pingback: Implement a Queue – Mike Scherbakov

Leave a Comment

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

Scroll to Top