VOOZH about

URL: https://www.geeksforgeeks.org/dsa/implement-a-stack-using-singly-linked-list/

⇱ Stack - Linked List Implementation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stack - Linked List Implementation

Last Updated : 13 Sep, 2025

A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. It can be implemented using a linked list, where each element of the stack is represented as a node. The head of the linked list acts as the top of the stack.

Declaration of Stack using Linked List

A stack can be implemented using a linked list where we maintain:

  • A Node structure/class that contains:
    data β†’ to store the element.
    next β†’ pointer/reference to the next node in the stack.
  • A pointer/reference top that always points to the current top node of the stack.
    Initially, top = null to represent an empty stack.

Operations on Stack using Linked List

Push Operation

Adds an item to the stack. Unlike array implementation, there is no fixed capacity in linked list. Overflow occurs only when memory is exhausted.

  •  A new node is created with the given value.
  • The new node’s next pointer is set to the current top.
  • The top pointer is updated to point to this new node.
πŸ‘ Push-elements-in-the-stack-1


Time Complexity: O(1)
Auxiliary Space: O(1)

Pop Operation

Removes the top item from the stack. If the stack is empty, it is said to be an Underflow condition.

  • Before deleting, we check if the stack is empty (top == NULL).
  • If the stack is empty, underflow occurs and deletion is not possible.
  • Otherwise, we store the current top node in a temporary pointer.
  • Move the top pointer to the next node.
  • Delete the temporary node to free memory.
πŸ‘ Pop-elements-from-the-stack


Time Complexity: O(1)
Auxiliary Space: O(1)

Peek (or Top) Operation

Returns the value of the top item without removing it from the stack.

  • If the stack is empty (top == NULL), then no element exists.
  • Otherwise, simply return the data of the node pointed by top.

Time Complexity: O(1)
Auxiliary Space: O(1)

isEmpty Operation

Checks whether the stack has no elements.

  • If the top pointer is NULL, it means the stack is empty and the function returns true.
  • Otherwise, it returns false.

Time Complexity: O(1)
Auxiliary Space: O(1)

Stack Implementation using Linked List


Output
Popped: 4
Top element: 3
Is stack empty: No
Current size: 3


πŸ‘ Advantages-of-Stack-using-Linked-List
Comment