-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list_cycle_test.go
69 lines (56 loc) · 1.18 KB
/
linked_list_cycle_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
Problem:
- Given the head of a singly linked list, write a function to determine
if it contains a cycle.
Approach:
- Have a slow pointer move one step at a time while the fast one move
2 steps at a time.
- If the linked list has a cycle, the fast pointer will catch the slow one.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/pcaruana/algo/common"
)
func TestHasCycle(t *testing.T) {
// define tests input.
t1 := common.NewListNode(1)
t1.AddNext(2)
t1.AddNext(3)
t2 := common.NewListNode(1)
t2.AddNext(2)
t2.AddNext(3)
t2.Next.Next.Next = t2
// define tests output.
tests := []struct {
in *common.ListNode
expected bool
}{
{t1, false},
{t2, true},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
hasCycle(tt.in),
)
}
}
func hasCycle(node *common.ListNode) bool {
// keep two pointers at the beginning.
slow := node
fast := node
// traverse until it hit the end of the list.
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
// if the fast pointer catches the slow one, there exists a cycle.
if fast.Value == slow.Value {
return true
}
}
return false
}