Skip to content

Commit 3fc5a06

Browse files
committed
141 accepted.
1 parent 73416cb commit 3fc5a06

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

Algorithms/0142.linked-list-cycle-ii/linked-list-cycle-ii.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@ import "github.com/aQuaYi/LeetCode-in-Go/kit"
66
type ListNode = kit.ListNode
77

88
func detectCycle(head *ListNode) *ListNode {
9+
headPre := &ListNode{
10+
Next: head,
11+
}
12+
return detect(headPre)
13+
}
914

15+
func detect(head *ListNode) *ListNode {
16+
hasSeen := make(map[*ListNode]bool)
17+
for head != nil && head.Next != nil {
18+
if hasSeen[head.Next] {
19+
return head.Next
20+
}
21+
hasSeen[head.Next] = true
22+
head = head.Next
23+
}
1024
return nil
1125
}

Algorithms/0142.linked-list-cycle-ii/linked-list-cycle-ii_test.go

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ var tcs = []struct {
1414
pos int
1515
}{
1616

17+
{
18+
[]int{1, 2, 3},
19+
-1,
20+
},
21+
1722
{
1823
[]int{3, 2, 0, -4},
1924
1,
@@ -24,20 +29,17 @@ var tcs = []struct {
2429
0,
2530
},
2631

27-
{
28-
[]int{1},
29-
-1,
30-
},
31-
3232
// 可以有多个 testcase
3333
}
3434

3535
func Test_detectCycle(t *testing.T) {
3636
ast := assert.New(t)
37-
3837
for _, tc := range tcs {
3938
head := kit.Ints2ListWithCycle(tc.ints, tc.pos)
40-
ans := head.GetNodeWith(tc.ints[tc.pos])
39+
var ans *ListNode
40+
if tc.pos >= 0 {
41+
ans = head.GetNodeWith(tc.ints[tc.pos])
42+
}
4143
ast.Equal(ans, detectCycle(head), "输入:%v", tc)
4244
}
4345
}

0 commit comments

Comments
 (0)