Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b6bf510

Browse files
author
Shuo
authored
Merge pull request #377 from openset/develop
Add: Linked List Cycle
2 parents 1ac41fa + 7177ee6 commit b6bf510

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,21 @@
11
package linked_list_cycle
2+
3+
import . "github.com/openset/leetcode/internal/kit"
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* type ListNode struct {
8+
* Val int
9+
* Next *ListNode
10+
* }
11+
*/
12+
func hasCycle(head *ListNode) bool {
13+
for p1, p2 := head, head; p1 != nil && p2 != nil; p1 = p1.Next {
14+
if p2 = p2.Next; p2 != nil {
15+
if p2 = p2.Next; p1 == p2 {
16+
return true
17+
}
18+
}
19+
}
20+
return false
21+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,55 @@
11
package linked_list_cycle
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/openset/leetcode/internal/kit"
7+
)
8+
9+
type caseType struct {
10+
input []int
11+
pos int
12+
expected bool
13+
}
14+
15+
func TestHasCycle(t *testing.T) {
16+
tests := [...]caseType{
17+
{
18+
input: []int{3, 2, 0, -4},
19+
pos: 1,
20+
expected: true,
21+
},
22+
{
23+
input: []int{1, 2},
24+
pos: 0,
25+
expected: true,
26+
},
27+
{
28+
input: []int{1, 2, 3, 4, 5},
29+
pos: -1,
30+
expected: false,
31+
},
32+
{
33+
input: []int{1},
34+
pos: -1,
35+
expected: false,
36+
},
37+
}
38+
for _, tc := range tests {
39+
input := SliceInt2ListNode(tc.input)
40+
p, curr := input, input
41+
for i := 0; curr != nil && tc.pos >= 0; i, curr = i+1, curr.Next {
42+
if i == tc.pos {
43+
p = curr
44+
}
45+
if curr.Next == nil {
46+
curr.Next = p
47+
break
48+
}
49+
}
50+
output := hasCycle(input)
51+
if output != tc.expected {
52+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
53+
}
54+
}
55+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /