Question
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Thinking
要判斷一Linked List是否有循環存在,可以使用弗洛伊德演算法(Floyd Cycle Detection Algorithm),亦被稱為龜兔賽跑算法(Tortoise and Hare Algorithm),即假設烏龜與兔子以不同速率前進,若這條路存在循環,則兩者必定會有相遇的時刻,在Linked List上的概念亦是如此,如下圖
My C# Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head) {
if (head == null || head.next == null) return false;
var tortoise = head;
var hare = head.next;
while(tortoise != hare)
{
if (hare == null || hare.next == null) return false;
tortoise = tortoise.next;
hare = hare.next.next;
}
return true;
}
}
Reference:Floyd判圈算法 - Wiki、Cycle Finding: Floyd's Algorithm