Implementation of Stack using Linked List in Java

A stack is a LIFO (Last In, First Out) data structure where elements are inserted and removed from the same end, called the top. While a stack is commonly implemented using a fixed-size array, it can also be backed by a linked list — which removes the size constraint entirely and allocates memory only as elements are pushed.

In this post, we implement a stack using a singly linked list in Java. Each push operation adds a new node at the head of the list, and each pop removes the head node — making both operations O(1).

Java Program: Stack Using Linked List

import java.io.*;

// A single node in the linked list backing the stack
class StackNode {
    int data;
    StackNode next;  // Pointer to the node below in the stack

    public StackNode(int value) {
        data = value;
        next = null;
    }
}

// Stack implementation using a singly linked list
class LinkedStack {
    StackNode top = null;  // Top of the stack; null means empty

    // Returns true if the stack has no elements
    public boolean isEmpty() {
        return (top == null);
    }

    // Pushes a new element onto the top of the stack
    public void push(int value) {
        StackNode newNode = new StackNode(value);
        if (isEmpty()) {
            top = newNode;          // First element: top points directly to it
        } else {
            newNode.next = top;     // New node points down to current top
            top = newNode;          // Update top to new node
        }
    }

    // Removes and returns the top element
    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack is empty - nothing to pop");
            return -1;
        }
        int value = top.data;
        top = top.next;  // Move top down to the next node
        return value;
    }

    // Returns the top element without removing it
    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty - nothing to peek");
            return -1;
        }
        return top.data;
    }

    // Displays all elements from top to bottom
    public void display() {
        if (isEmpty()) {
            System.out.println("Stack is empty");
            return;
        }
        StackNode current = top;
        System.out.print("Stack (top to bottom): ");
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

public class StackUsingLinkedList {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        LinkedStack stack = new LinkedStack();
        int choice;

        do {
            System.out.println();
            System.out.println("--- Stack (Linked List) Menu ---");
            System.out.println("1. Push (insert element)");
            System.out.println("2. Pop (remove element)");
            System.out.println("3. Peek (view top element)");
            System.out.println("4. Display stack");
            System.out.println("5. Exit");
            System.out.print("Enter choice: ");
            choice = Integer.parseInt(reader.readLine());

            switch (choice) {
                case 1:
                    System.out.print("Enter element to push: ");
                    int element = Integer.parseInt(reader.readLine());
                    stack.push(element);
                    System.out.println("Pushed: " + element);
                    break;
                case 2:
                    int popped = stack.pop();
                    if (popped != -1) System.out.println("Popped element: " + popped);
                    break;
                case 3:
                    int peeked = stack.peek();
                    if (peeked != -1) System.out.println("Top element: " + peeked);
                    break;
                case 4:
                    stack.display();
                    break;
                case 5:
                    System.out.println("Exiting...");
                    break;
                default:
                    System.out.println("Invalid choice");
            }
        } while (choice != 5);
    }
}

How the Code Works

  1. StackNode class — Each node holds an integer data value and a next pointer to the node below it in the stack.
  2. push() — Creates a new node, sets its next to the current top, and then updates top to the new node. This is like prepending to the linked list.
  3. pop() — Saves the top node’s value, then advances top to top.next. The old top node becomes eligible for garbage collection.
  4. peek() — Returns top.data without modifying the stack. Useful for inspecting what will be popped next.
  5. display() — Traverses from top through all next pointers, printing each element from top to bottom.
  6. No overflow — Unlike an array-based stack, this implementation grows dynamically with each push, limited only by available heap memory.

Sample Output

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 1
Enter element to push: 10
Pushed: 10

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 1
Enter element to push: 20
Pushed: 20

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 1
Enter element to push: 30
Pushed: 30

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 1
Enter element to push: 40
Pushed: 40

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 4
Stack (top to bottom): 40 30 20 10 

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 3
Top element: 40

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 2
Popped element: 40

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 2
Popped element: 30

--- Stack (Linked List) Menu ---
1. Push (insert element)
2. Pop (remove element)
3. Peek (view top element)
4. Display stack
5. Exit
Enter choice: 4
Stack (top to bottom): 20 10

Output Explanation

  • Elements 10, 20, 30, 40 are pushed in that order. The top of the stack is always the most recently pushed element.
  • The display shows them in reverse push order (40 30 20 10) — top to bottom — confirming LIFO behavior.
  • After popping 40 and 30, the remaining stack is 20 10, with 20 now at the top.

See Also

Conclusion

Implementing a stack with a linked list is a clean, dynamically-sized alternative to the array-based approach. It avoids stack overflow due to fixed capacity and is particularly useful when the maximum number of elements is unknown at compile time. The trade-off is slightly more memory per element (the next pointer) and less cache-friendly memory access compared to a contiguous array.

One thought on “Implementation of Stack using Linked List in Java”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.