Mid From PDF Coding C# Coding Interview

Detect a cycle in a linked list and return the node where the cycle?

begins

public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) { val = x; next = null; }
}
ListNode DetectCycle(ListNode head) {
if (head == null) return null;
ListNode slow = head, fast = head;

Follow on:

// Detect cycle using Floyd's Tortoise and Hare

while (fast != null && fast.next != null) {

slow = slow.next;
fast = fast.next.next;
if (slow == fast) { // cycle detected
ListNode ptr = head;

while (ptr != slow) {

ptr = ptr.next;
slow = slow.next;
}
return ptr; // start node of cycle
}
}
return null; // no cycle
}

Explanation:

First detect cycle meeting point with two pointers. Then find start node by moving one

pointer from head and one from meeting point until they meet.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details