/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funchasCycle(head *ListNode) bool { m :=make(map[*ListNode]bool)for head !=nil {if _,found := m[head]; found {returntrue } m[head] =true head = head.Next }returnfalse}
Solution 2 (Go)
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funchasCycle(head *ListNode) bool { tortoise, hare := head, headfor tortoise !=nil&& hare !=nil&& hare.Next !=nil { tortoise = tortoise.Next hare = hare.Next.Nextif tortoise == hare {returntrue } }returnfalse}
Solution 3 (Java)
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */publicclassSolution { /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */publicbooleanhasCycle(ListNode head) {if (head ==null||head.next==null)returnfalse;ListNode slow = head;ListNode fast = head;while (fast.next!=null&&fast.next.next!=null) { slow =slow.next; fast =fast.next.next;if (slow == fast) returntrue; }returnfalse; }}
Floyd's tortoise and hare cycle-finding algorithm
The tortoise move by 1 step each time and the hare moves by 2 steps at a time. If there is a cycle, the hare will eventually catch the tortoise at a position.
A simple idea of the proof can be tracking the gap between the tortoise and the hare. By construction, the gap increases by 1 each iteration. Eventually, the gap with become n, where n is the number of elements in the cycle (not the whole list). This is the time when the tortoise and the hare meet. More proofs: