Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 26, 2020 08:26
Show Gist options
  • Select an option

  • Save alldroll/efec87ebcc845e59efc1b8f8057cf8d6 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/efec87ebcc845e59efc1b8f8057cf8d6 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/linked-list-cycle-ii/ccccccccc
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func detectCycle(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return nil
}
hare := head
tortoise := head
for tortoise != nil && hare != nil && hare.Next != nil {
tortoise = tortoise.Next // f(xi)
hare = hare.Next.Next // f(f(xi))
if hare == tortoise {
break
}
}
if hare != tortoise {
return nil
}
tortoise = head
for tortoise != hare {
tortoise = tortoise.Next
hare = hare.Next
}
return hare
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment