-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathlinked_list_cycle_test.go
70 lines (56 loc) · 1.47 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
70
/*
Problem:
- Determine if a singly-linked list has a cycle.
Approach:
- Keep two pointers starting at the first node such that: every time one moves
one node ahead, the other moves 2 nodes ahead.
- If the linked list has a cycle, the faster one will catch up with the slow
one. Otherwise, the faster one will each the end.
Solution:
- Keep two pointers, a slow one and a fast one, at the beginning.
- Traverse the list and move the fast one 2 nodes once the slow one move a node.
- If the fast one catches the slow one, there exists a cycle.
Cost:
- O(n) time and O(1) space.
*/
package interviewcake
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestContainCycle(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, containCycle(tt.in))
}
}
func containCycle(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 && fast.Next.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
}