Java Linked List Program · OT37
Detect a Cycle in a Linked List in Java
If a list has a loop, a pointer moving two steps at a time eventually catches a pointer moving one step at a time. If it reaches the end, there is no loop.
Problem Statement
Return true if a singly linked list contains a cycle, meaning some node's next points back to an earlier node.
Use constant extra memory if possible, and do not modify the list.
Input/Output Examples
1→2→3→4, then back to 2OutputtrueExplanation: 4 points back to 2.1→2→3→4OutputfalseExplanation: the last node points to null.5, pointing to itselfOutputtrueExplanation: the smallest possible cycle.Visual Explanation
- Startpositionsslow 1fast 1
- Step 1positionsslow 2fast 3
- Step 2positionsslow 3fast 2fast wrapped: 3 → 4 → 2
- Step 3positionsslow 4fast 4same node cycle
- Donetrue
Once both pointers are inside the loop, the gap between them shrinks by one each step, so they must meet within one lap. Without a loop, the fast pointer simply reaches null.
Approaches
Floyd's method uses two pointers and no extra memory. The set method remembers every node visited.
Approach 1: Floyd's Tortoise and Hare (Recommended)
Idea: move slow one step and fast two steps; a cycle exists if they ever point to the same node.
- Start both at the head.
- While
fastandfast.nextexist, advance both. - Return
trueif they meet;falseiffastruns out.
Time: O(n) · Space: O(1).
Approach 2: HashSet of Visited Nodes
Idea: add every node to a set; finding one that is already there means the list loops.
- Walk the list.
- If
seen.add(node)returnsfalse, returntrue. - Return
falseat the end of the list.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Floyd's Tortoise and Hare (Recommended)
Comparing with == checks node identity, which is exactly what a cycle means.
public class CycleFloyd {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
static Node of(int... values) {
Node dummy = new Node(0);
Node t = dummy;
for (int v : values) {
t = t.next = new Node(v);
}
return dummy.next;
}
static String show(Node n) {
if (n == null) {
return "(empty)";
}
StringBuilder sb = new StringBuilder();
for (; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? "->" : "");
}
return sb.toString();
}
// If there is a loop, the fast pointer eventually laps the slow one
static boolean hasCycle(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
static Node withCycle(int loopTo, int... values) {
Node head = of(values);
Node tail = head;
Node target = null;
int i = 0;
for (Node n = head; n != null; n = n.next, i++) {
if (i == loopTo) {
target = n;
}
tail = n;
}
tail.next = target; // close the loop (null means no loop)
return head;
}
public static void main(String[] args) {
System.out.println("1->2->3->4, back to 2 -> " + hasCycle(withCycle(1, 1, 2, 3, 4)));
System.out.println("1->2->3->4 -> " + hasCycle(withCycle(-1, 1, 2, 3, 4)));
System.out.println("5, back to itself -> " + hasCycle(withCycle(0, 5)));
}
}
1->2->3->4, back to 2 -> true 1->2->3->4 -> false 5, back to itself -> true
Time complexity: O(n) · Space complexity: O(1).
Approach 2: HashSet of Visited Nodes
Straightforward, and it can also report the first repeated node directly.
import java.util.HashSet;
import java.util.Set;
public class CycleHashSet {
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
static Node of(int... values) {
Node dummy = new Node(0);
Node t = dummy;
for (int v : values) {
t = t.next = new Node(v);
}
return dummy.next;
}
static String show(Node n) {
if (n == null) {
return "(empty)";
}
StringBuilder sb = new StringBuilder();
for (; n != null; n = n.next) {
sb.append(n.val).append(n.next != null ? "->" : "");
}
return sb.toString();
}
// Remember every node visited; reaching one again means the list loops
static boolean hasCycle(Node head) {
Set<Node> seen = new HashSet<>();
for (Node n = head; n != null; n = n.next) {
if (!seen.add(n)) {
return true;
}
}
return false;
}
static Node withCycle(int loopTo, int... values) {
Node head = of(values);
Node tail = head;
Node target = null;
int i = 0;
for (Node n = head; n != null; n = n.next, i++) {
if (i == loopTo) {
target = n;
}
tail = n;
}
tail.next = target;
return head;
}
public static void main(String[] args) {
System.out.println("1->2->3->4, back to 2 -> " + hasCycle(withCycle(1, 1, 2, 3, 4)));
System.out.println("1->2->3->4 -> " + hasCycle(withCycle(-1, 1, 2, 3, 4)));
System.out.println("5, back to itself -> " + hasCycle(withCycle(0, 5)));
}
}
1->2->3->4, back to 2 -> true 1->2->3->4 -> false 5, back to itself -> true
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Floyd's Tortoise and Hare | O(n) | O(1) |
| HashSet of Visited Nodes | O(n) | O(n) |
Here n is the number of nodes. Both approaches finish within a constant number of passes; only the set needs memory for every node.
Interview Tips and Recommended Approach
- Check both
fastandfast.nextbefore moving two steps. - Compare references, not values. Two nodes can hold the same value.
- Know the follow-up. Restarting one pointer at the head and moving both one step finds where the cycle begins.
- Do not mark nodes by changing their values or links; that modifies the input.
Recommended Approach: Floyd's Tortoise and Hare
Why: it detects any cycle with two pointers and no extra memory, and it extends naturally to finding where the cycle starts.