Time: O(n) Space: O(1)
(head *ListNode)
| 5 | // Time: O(n) |
| 6 | // Space: O(1) |
| 7 | func hasCycle(head *ListNode) bool { |
| 8 | if head == nil || head.Next == nil { |
| 9 | return false |
| 10 | } |
| 11 | |
| 12 | // use the rabbit and turtle analogy |
| 13 | // if there as a cycle, eventually the rabbit will meet back up with the turtle |
| 14 | turtle := head |
| 15 | rabbit := head.Next |
| 16 | for rabbit != nil && turtle != nil { |
| 17 | if turtle == rabbit { |
| 18 | return true |
| 19 | } |
| 20 | |
| 21 | if rabbit.Next == nil { |
| 22 | rabbit = nil |
| 23 | } else { |
| 24 | rabbit = rabbit.Next.Next |
| 25 | } |
| 26 | |
| 27 | if turtle.Next == nil { |
| 28 | turtle = nil |
| 29 | } else { |
| 30 | turtle = turtle.Next |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return false |
| 35 | } |
no outgoing calls