Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 0d708a3

Browse files
committed
141 wrong answer
1 parent af17dd7 commit 0d708a3

File tree

7 files changed

+203
-38
lines changed

7 files changed

+203
-38
lines changed
11 KB
Loading
4.47 KB
Loading
1.92 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# [141. Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)
2+
3+
Given a linked list, determine if it has a cycle in it.
4+
5+
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
6+
7+
Example 1:
8+
9+
```text
10+
Input: head = [3,2,0,-4], pos = 1
11+
Output: true
12+
Explanation: There is a cycle in the linked list, where tail connects to the second node.
13+
```
14+
15+
![1](1.png)
16+
17+
Example 2:
18+
19+
```text
20+
Input: head = [1,2], pos = 0
21+
Output: true
22+
Explanation: There is a cycle in the linked list, where tail connects to the first node.
23+
```
24+
25+
![2](2.png)
26+
27+
Example 3:
28+
29+
```text
30+
Input: head = [1], pos = -1
31+
Output: false
32+
Explanation: There is no cycle in the linked list.
33+
```
34+
35+
![3](3.png)
36+
37+
Follow up:
38+
39+
- Can you solve it using O(1) (i.e. constant) memory?
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package problem0141
2+
3+
import "github.com/aQuaYi/LeetCode-in-Go/kit"
4+
5+
// ListNode is pre-defined...
6+
type ListNode = kit.ListNode
7+
8+
func hasCycle(head *ListNode) bool {
9+
if head == nil {
10+
return false
11+
}
12+
slow, fast := head, head
13+
for fast != nil && fast.Next != nil && slow != fast {
14+
slow, fast = slow.Next, fast.Next.Next
15+
}
16+
return slow == fast && head.Next != nil
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package problem0141
2+
3+
import (
4+
"testing"
5+
6+
"github.com/aQuaYi/LeetCode-in-Go/kit"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
// tcs is testcase slice
12+
var tcs = []struct {
13+
head []int
14+
pos int
15+
ans bool
16+
}{
17+
18+
{
19+
[]int{3, 2, 0, -4},
20+
1,
21+
true,
22+
},
23+
24+
{
25+
[]int{1, 2},
26+
0,
27+
true,
28+
},
29+
30+
{
31+
[]int{},
32+
-1,
33+
false,
34+
},
35+
36+
{
37+
[]int{1},
38+
-1,
39+
false,
40+
},
41+
42+
// 可以有多个 testcase
43+
}
44+
45+
func Test_hasCycle(t *testing.T) {
46+
ast := assert.New(t)
47+
48+
for _, tc := range tcs {
49+
head := kit.Ints2ListWithCycle(tc.head, tc.pos)
50+
ast.Equal(tc.ans, hasCycle(head), "输入:%v", tc)
51+
}
52+
}
53+
54+
func Benchmark_hasCycle(b *testing.B) {
55+
for i := 0; i < b.N; i++ {
56+
for _, tc := range tcs {
57+
head := kit.Ints2ListWithCycle(tc.head, tc.pos)
58+
hasCycle(head)
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)