Created
February 26, 2020 08:26
-
-
Save alldroll/efec87ebcc845e59efc1b8f8057cf8d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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