Mark As Completed Discussion

To detect a cycle in a linked list, we can use the "fast and slow pointers" technique. This technique involves initializing two pointers: slow and fast. The slow pointer moves one node at a time, while the fast pointer moves two nodes at a time.

If the linked list contains a cycle, the slow and fast pointers will eventually meet at the same node. To determine the starting node of the cycle, we reset the slow pointer to the head of the list and then move both pointers at a rate of one node per step. The point at which they meet again is the starting node of the cycle.

Here's an example of Java code that detects a cycle in a linked list:

TEXT/X-JAVA
1public class LinkedList {
2
3    static Node head;
4
5    static class Node {
6        int data;
7        Node next;
8
9        Node(int d) {
10            data = d;
11            next = null;
12        }
13    }
14
15    // Function to detect and return the starting node of a cycle in the linked list
16    static Node detectCycle(Node head) {
17        if (head == null || head.next == null) {
18            return null;
19        }
20
21        Node slow = head;
22        Node fast = head;
23        while (fast != null && fast.next != null) {
24            slow = slow.next;
25            fast = fast.next.next;
26
27            // If slow and fast pointers meet, there is a cycle
28            if (slow == fast) {
29
30                // Reset slow pointer to head
31                slow = head;
32
33                /* Move both slow and fast pointers one node at a time
34                   until they meet at the starting node of the cycle */
35                while (slow != fast) {
36                    slow = slow.next;
37                    fast = fast.next;
38                }
39                return slow;
40            }
41        }
42
43        // If no cycle is present in the linked list
44        return null;
45    }
46
47    public static void main(String[] args) {
48        LinkedList list = new LinkedList();
49
50        // Create a linked list with a cycle
51        list.head = new Node(1);
52        list.head.next = new Node(2);
53        list.head.next.next = new Node(3);
54        list.head.next.next.next = new Node(4);
55        list.head.next.next.next.next = new Node(5);
56        list.head.next.next.next.next.next = list.head.next;
57
58        Node cycleStart = detectCycle(head);
59        if (cycleStart != null) {
60            System.out.println("Cycle found at node: " + cycleStart.data);
61        } else {
62            System.out.println("No cycle found in the linked list");
63        }
64    }
65}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment