Linked List Cycle - Java Solution

1. Introduction

In this post, we explore a fundamental problem in linked list operations known as the "Linked List Cycle" problem. It involves determining whether a given linked list contains a cycle — a condition where a node's next pointer points to an earlier node in the list, creating a loop.


Given the head of a linked list, the task is to determine if the linked list has a cycle. A cycle occurs if a node in the list can be reached again by continuously following the next pointer. The challenge is to identify the presence of such a cycle without knowing the position of the tail's next pointer.

2. Solution Steps

1. Use two pointers, slow and fast, both initially pointing to the head of the list.

2. Move slow by one step and fast by two steps in each iteration.

3. If the linked list has a cycle, slow and fast will eventually meet; otherwise, fast will reach the end of the list.

4. Return true if slow and fast meet; otherwise, return false.

3. Code Program

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;

public class LinkedListCycle {
    public static void main(String[] args) {
        // Example use case
        ListNode head = new ListNode(3); = new ListNode(2); = new ListNode(0); = new ListNode(-4); =; // Creating a cycle

        System.out.println(hasCycle(head)); // Test the function

    // Function to detect a cycle in a linked list
    public static boolean hasCycle(ListNode head) {
        if (head == null) return false;

        ListNode slow = head;
        ListNode fast =;
        while (slow != fast) {
            if (fast == null || == null) {
                return false;
            slow =;
            fast =;
        return true;




1. hasCycle: This function checks for the presence of a cycle in the linked list.

2. Two pointers, slow and fast, are used. slow moves one step at a time, while fast moves two steps.

3. If there's a cycle, slow and fast will eventually point to the same node, indicating a cycle.

4. If fast reaches the end of the list (null), it means there's no cycle.

5. The function returns true if a cycle is detected, otherwise false.

6. This approach, known as Floyd's Tortoise and Hare algorithm, efficiently detects cycles without using extra space for storage.