-
Notifications
You must be signed in to change notification settings - Fork 376
/
middle_list_test.go
68 lines (56 loc) · 1.08 KB
/
middle_list_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
/*
Problem:
- Given the head of a singly linked list, write a function to return the
middle value.
Approach:
- Have a slow pointer move one step at a time while the fast one move
2 steps at a time.
- Once the fast one reaches the end, the slow is in the middle.
Cost:
- O(n) time, O(1) space.
*/
package gtci
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestFindMid(t *testing.T) {
// define tests input.
t1 := common.NewListNode(1)
t1.AddNext(2)
t1.AddNext(3)
t1.AddNext(4)
t1.AddNext(5)
t1.AddNext(6)
t2 := common.NewListNode(1)
t2.AddNext(2)
t2.AddNext(3)
t2.AddNext(4)
t2.AddNext(5)
// define tests output.
tests := []struct {
in *common.ListNode
expected int
}{
{t1, 4},
{t2, 3},
}
for _, tt := range tests {
common.Equal(
t,
tt.expected,
findMid(tt.in),
)
}
}
func findMid(node *common.ListNode) int {
// 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
}
return slow.Value
}