Skip to content

Commit 7566094

Browse files
committed
Add: Linked List Cycle
1 parent db4ab6c commit 7566094

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,23 @@
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; p1 = p1.Next {
14+
if p2 != nil && p2.Next != nil {
15+
if p2 = p2.Next.Next; p1 == p2 {
16+
return true
17+
}
18+
} else {
19+
return false
20+
}
21+
}
22+
return false
23+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,50 @@
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},
29+
pos: -1,
30+
expected: false,
31+
},
32+
}
33+
for _, tc := range tests {
34+
input := SliceInt2ListNode(tc.input)
35+
p, curr := input, input
36+
for i := 0; curr != nil && tc.pos >= 0; i, curr = i+1, curr.Next {
37+
if i == tc.pos {
38+
p = curr
39+
}
40+
if curr.Next == nil {
41+
curr.Next = p
42+
break
43+
}
44+
}
45+
output := hasCycle(input)
46+
if output != tc.expected {
47+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)