Representation of a Stack as a Linked List in Java

Representation of a Stack as a Linked List

Representation of a Stack as a Linked List in Java is a practical way to implement the stack data structure without the fixed size limitation of arrays.

Instead of storing elements in a continuous memory block, we store each element inside a node and connect nodes using references. This makes stack growth dynamic and helps you understand how real world stacks can be built efficiently using pointers (references) and linked structures.

representation of a stack as a linked list in java

Representation of a Stack as a Linked List in Java

Understanding Stack as a Linked List:

Stack can also be represented by using a linked list. We know that in the case of arrays we face a limitation , i.e , array is a data structure of limited size.

Hence before using an array to represent a stack we will have to consider an enough amount of space to hold the memory required by the stack.

Working of Stack as a Linked List in Java

Core idea:

We maintain a reference called top (or head) that points to the first node of the linked list.

  1. Head node represents the top of the stack.
  2. Every push inserts a node at the head.
  3. Every pop removes a node from the head.

This is the most efficient approach because insert/delete at the head in a singly linked list is O(1).

representation of a stack as a linked list

Operations in Stack as a Linked List

Following are common operations implemented on the stack:

  1. push(x): create a new node, link it to old top, update top
  2. pop(): remove the top node and return its data
  3. peek(): return the top element without removing it
  4. isEmpty(): check if top is null
  5. size() (optional but useful): track count of nodes

Stack Operations in Linked List conditions:

Data structure: Node

Each node contains:

  • data → the value stored
  • next → reference to the next node

Stack pointer:

Node top → reference to the current top node

Learn DSA

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Algorithm for Stack Operation in Java

Algorithm:

  1. Create a Node structure with:
    • data (value)
    • next (link to next node)
  2. Maintain:
    • top → points to the first node (top of stack)

    • size → number of elements (optional)

Operations:

1) PUSH(value):

  1. Create a new node newNode with newNode.data = value.
  2. Point newNode.next to the current top.
  3. Update top to newNode.
  4. Increase size by 1.

2) POP():

  1. If top == null, report Stack Underflow (stack is empty) and stop.
  2. Store poppedValue = top.data.
  3. Move top to the next node: top = top.next.
  4. Decrease size by 1.
  5. Return poppedValue.

3) PEEK():

  1. If top == null, report stack is empty and stop.
  2. Return top.data.

4) ISEMPTY():

  1. If top == null, return true.
  2. Otherwise return false.

Implementing Stack as a Linked List in Java

This program:

  1. Implements a stack using a singly linked list (head as top)
  2. Supports push, pop, peek, isEmpty, size
  3. Demonstrates sample operations and prints output

Java Code:

Run

import java.util.Scanner;

public class StackUsingLinkedList {

    // Node class for the linked list
    private static class Node {
        int data;
        Node next;

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

    private Node top;     // Top of stack
    private int size;     // Optional: track number of elements

    public StackUsingLinkedList() {
        this.top = null;
        this.size = 0;
    }

    // Push operation: O(1)
    public void push(int value) {
        Node newNode = new Node(value);
        newNode.next = top;
        top = newNode;
        size++;
    }

    // Pop operation: O(1)
    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack Underflow: Cannot pop from an empty stack.");
            return Integer.MIN_VALUE;
        }
        int poppedValue = top.data;
        top = top.next;
        size--;
        return poppedValue;
    }

    // Peek operation: O(1)
    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty: Nothing to peek.");
            return Integer.MIN_VALUE;
        }
        return top.data;
    }

    // isEmpty operation: O(1)
    public boolean isEmpty() {
        return top == null;
    }

    // size operation: O(1)
    public int size() {
        return size;
    }

    // Display stack elements from top to bottom: O(n)
    public void display() {
        if (isEmpty()) {
            System.out.println("Stack is empty.");
            return;
        }

        System.out.print("Stack (top -> bottom): ");
        Node current = top;
        while (current != null) {
            System.out.print(current.data);
            if (current.next != null) System.out.print(" -> ");
            current = current.next;
        }
        System.out.println();
    }

    // Demo main
    public static void main(String[] args) {
        StackUsingLinkedList stack = new StackUsingLinkedList();

        // Example: fixed set of operations (simple beginner demo)
        stack.push(10);
        stack.push(20);
        stack.push(30);

        stack.display();

        System.out.println("Peek: " + stack.peek());
        System.out.println("Pop: " + stack.pop());
        System.out.println("Pop: " + stack.pop());

        stack.display();
        System.out.println("Current size: " + stack.size());

        // Optional: show pop on empty behavior quickly
        System.out.println("Pop: " + stack.pop());
        System.out.println("Pop: " + stack.pop()); // underflow example
    }
}

Output

Stack (top -> bottom): 30 -> 20 -> 10
Peek: 30
Pop: 30
Pop: 20
Stack (top -> bottom): 10
Current size: 1
Pop: 10
Stack Underflow: Cannot pop from an empty stack.
Pop: -2147483648

Conclusion:

Analysis of Space and Time complexity for Working with Stack as a Linked List:

OperationTimeExtra Space
pushO(1)O(1) per pushed node
popO(1)O(1)
peekO(1)O(1)
isEmptyO(1)O(1)

When to Prefer Linked List vs Array for Stack?

  1. Prefer linked list when:
  • You do not know the maximum stack size in advance
  • You want dynamic growth without manual resizing
  • You want O(1) push/pop without overflow from a fixed array size

2. Prefer array when:

  • You know the maximum size upfront
  • You want contiguous memory (often faster in practice due to cache locality)
  • You want minimal per-node memory overhead (no next pointer)

Frequently Asked Questions

Answer:

Representation of a Stack as a Linked List in Java means implementing stack operations (push, pop, peek) using linked list nodes, where the head node acts as the stack top and elements are inserted/removed from that end.

Answer:

Because arrays have a fixed size, which can cause overflow when the stack grows. A linked list grows dynamically as memory is available, removing the fixed capacity restriction.

Answer:

Both push and pop are O(1) when implemented at the head (top) of the linked list, because they only update a few references.

Answer:

Underflow happens when you try to pop() or peek() while the stack is empty (top == null). A correct implementation checks isEmpty() before removing or reading.

Answer:

Linked list nodes store an extra reference (next), so there is additional per element overhead compared to arrays. However, it prevents unused pre allocated space and supports dynamic growth.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Circular Linked List

  • Introduction to Circular Linked List
    Click Here
  • Circular Linked List Applications
    Click Here
  • Circular Linked List in –
    C | C++ | Java
  • Insertion in Circular Linked List –
    C | C++ | Java
  • Insertion at the beginning–
    C | C++ | Java
  • Insertion at the end –
    C | C++ | Java
  • Insertion at nth position –
    C | C++ | Java
  • Deletion in Circular Linked List –
    C | C++ | Java
  • Deletion from beginning in Circular Linked List –
    C | C++ | Java
  • Deletion from nth position in Circular Linked List –
  • Deletion from end in Circular Linked List –
    C | C++ | Java
  • Insertion and Deletion in Circular Linked List – C | C++ | Java
  • Split a Circular Linked List in two halves –
    C | C++ | Java
  • Count nodes in Circular Linked List –
    C | C++ | Java
  • Sorted Insert In Circular Linked List –
    C | C++ | Java
  • Insertion in the middle in Circular Linked List –
    C | C++ | Java

Circular Linked List