MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / hasCycle

Function hasCycle

linked_list_cycle_141/solution.go:7–35  ·  view source on GitHub ↗

Time: O(n) Space: O(1)

(head *ListNode)

Source from the content-addressed store, hash-verified

5// Time: O(n)
6// Space: O(1)
7func 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}

Callers 3

Test_hasCycle1Function · 0.85
Test_hasCycle2Function · 0.85
Test_hasCycl32Function · 0.85

Calls

no outgoing calls

Tested by 3

Test_hasCycle1Function · 0.68
Test_hasCycle2Function · 0.68
Test_hasCycl32Function · 0.68