1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Circular Linked List
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Circular Linked List

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Circular Linked List

Overview

A Circular Linked List is a variation of a linked list in which the last node points back to the first node, forming a complete circle. There is no null at the end of the list.

Circular lists can be singly linked or doubly linked. The primary advantage of a circular list is that any node can be a starting point, and you can traverse the entire list starting from absolutely anywhere. This is particularly useful in applications that require continuous looping, like an OS round-robin task scheduler or a multiplayer board game turn system.

However, this infinite loop property makes traversal dangerous. If you write a standard while(current != null) loop, your program will get stuck in an infinite loop and crash. You must always maintain a reference to the starting node and stop traversing when current.next == startNode.

Syntax

Building a Circular Singly Linked List
java
public class CircularLinkedList {
    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }
    
    Node tail = null; // In circular lists, tracking the tail is more useful than head
    
    public void add(int data) {
        Node newNode = new Node(data);
        if (tail == null) {
            tail = newNode;
            tail.next = tail; // Point to itself!
        } else {
            newNode.next = tail.next; // New node points to the head
            tail.next = newNode;      // Old tail points to new node
            tail = newNode;           // New node becomes the tail
        }
    }
    
    public void printList() {
        if (tail == null) return;
        
        Node head = tail.next;
        Node current = head;
        
        do {
            System.out.print(current.data + " -> ");
            current = current.next;
        } while (current != head); // Stop when we complete the circle!
        
        System.out.println("(back to start)");
    }
}

Common Pitfalls

  • Infinite loops during traversal. The standard while (current != null) pattern does not work because there is no null in a circular list. You must use a do-while loop and check if current != head.
  • Losing track of the list bounds. Since it's a circle, the concepts of 'head' and 'tail' are purely logical, not structural. If your pointer management is sloppy during insertions or deletions, you can easily orphan nodes or break the circle.
  • Complexity in deleting nodes. Deleting the head node requires traversing the entire list to update the tail's next pointer to the new head (unless it's doubly linked), making it O(N) time.

Interview Questions

Why do implementations of Circular Linked Lists often maintain a pointer to the tail instead of the head?

If you only have a head pointer, appending to the end takes O(N) time because you must traverse the whole circle to find the tail to update its next pointer. If you keep a tail pointer, you have instant O(1) access to BOTH the tail and the head (since tail.next == head). This makes O(1) insertions at both ends possible.

How do you split a Circular Linked List into two equal halves?

Use the Fast and Slow Pointer technique. Move fast by two steps and slow by one step. When fast.next == head or fast.next.next == head, the slow pointer is at the midpoint. You then break the circle and re-wire the pointers to form two separate circular lists.

Real-World Example

A multiplayer game turn system. Players sit in a circle, and when one player's turn ends, it goes to the next. If a player leaves the game, their node is deleted, and the circle closes. There is no 'end' to the list until the game finishes.

example
java
class GameState {
    PlayerNode currentPlayer;
    
    public void nextTurn() {
        // Instantly move to the next player, looping back seamlessly
        currentPlayer = currentPlayer.next;
        System.out.println("It's now " + currentPlayer.name + "'s turn!");
    }
    
    public void playerLeft(PlayerNode player) {
        // Find player and remove them, bridging the circle
        // ... deletion logic ...
    }
}

Check Your Knowledge

Test your understanding of Circular Linked List with these quick questions.

Question 1

What is the stopping condition for traversing a full Circular Linked List?

Question 2

Why is tracking the `tail` pointer better than the `head` pointer in a Circular List?

Question 3

Which loop structure is safest and most commonly used to traverse a Circular Linked List?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Circular Linked List

Overview

A Circular Linked List is a variation of a linked list in which the last node points back to the first node, forming a complete circle. There is no null at the end of the list.

Circular lists can be singly linked or doubly linked. The primary advantage of a circular list is that any node can be a starting point, and you can traverse the entire list starting from absolutely anywhere. This is particularly useful in applications that require continuous looping, like an OS round-robin task scheduler or a multiplayer board game turn system.

However, this infinite loop property makes traversal dangerous. If you write a standard while(current != null) loop, your program will get stuck in an infinite loop and crash. You must always maintain a reference to the starting node and stop traversing when current.next == startNode.

Syntax

Building a Circular Singly Linked List
java
public class CircularLinkedList {
    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }
    
    Node tail = null; // In circular lists, tracking the tail is more useful than head
    
    public void add(int data) {
        Node newNode = new Node(data);
        if (tail == null) {
            tail = newNode;
            tail.next = tail; // Point to itself!
        } else {
            newNode.next = tail.next; // New node points to the head
            tail.next = newNode;      // Old tail points to new node
            tail = newNode;           // New node becomes the tail
        }
    }
    
    public void printList() {
        if (tail == null) return;
        
        Node head = tail.next;
        Node current = head;
        
        do {
            System.out.print(current.data + " -> ");
            current = current.next;
        } while (current != head); // Stop when we complete the circle!
        
        System.out.println("(back to start)");
    }
}

Common Pitfalls

  • Infinite loops during traversal. The standard while (current != null) pattern does not work because there is no null in a circular list. You must use a do-while loop and check if current != head.
  • Losing track of the list bounds. Since it's a circle, the concepts of 'head' and 'tail' are purely logical, not structural. If your pointer management is sloppy during insertions or deletions, you can easily orphan nodes or break the circle.
  • Complexity in deleting nodes. Deleting the head node requires traversing the entire list to update the tail's next pointer to the new head (unless it's doubly linked), making it O(N) time.

Interview Questions

Why do implementations of Circular Linked Lists often maintain a pointer to the tail instead of the head?

If you only have a head pointer, appending to the end takes O(N) time because you must traverse the whole circle to find the tail to update its next pointer. If you keep a tail pointer, you have instant O(1) access to BOTH the tail and the head (since tail.next == head). This makes O(1) insertions at both ends possible.

How do you split a Circular Linked List into two equal halves?

Use the Fast and Slow Pointer technique. Move fast by two steps and slow by one step. When fast.next == head or fast.next.next == head, the slow pointer is at the midpoint. You then break the circle and re-wire the pointers to form two separate circular lists.

Real-World Example

A multiplayer game turn system. Players sit in a circle, and when one player's turn ends, it goes to the next. If a player leaves the game, their node is deleted, and the circle closes. There is no 'end' to the list until the game finishes.

example
java
class GameState {
    PlayerNode currentPlayer;
    
    public void nextTurn() {
        // Instantly move to the next player, looping back seamlessly
        currentPlayer = currentPlayer.next;
        System.out.println("It's now " + currentPlayer.name + "'s turn!");
    }
    
    public void playerLeft(PlayerNode player) {
        // Find player and remove them, bridging the circle
        // ... deletion logic ...
    }
}

Check Your Knowledge

Test your understanding of Circular Linked List with these quick questions.

Question 1

What is the stopping condition for traversing a full Circular Linked List?

Question 2

Why is tracking the `tail` pointer better than the `head` pointer in a Circular List?

Question 3

Which loop structure is safest and most commonly used to traverse a Circular Linked List?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A