Approach: Using Floyd’s Cycle-Finding Algorithm.
public LinkedListNode HasCycle()
{
if (this.Head == null)
{
return null;
}
LinkedListNode slow = this.Head, fast = this.Head;
while (fast != null)
{
slow = slow.Next;
fast = fast.Next;
if (fast != null)
{
fast = fast.Next;
}
if (slow == fast)
{
break;
}
}
if (fast == null) // No cycle
{
return null;
}
slow = this.Head;
while(slow != fast)
{
slow = slow.Next;
fast = fast.Next;
}
return slow;
}
No comments:
Post a Comment