Skip to content

Commit 0b7820a

Browse files
committed
add another solution of Linked List Cycle
1 parent 15a283c commit 0b7820a

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

go/linked_list_cycle.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
package main
33

44
// `https://github.com/ryo-devz/LeetCode/pull/1#discussion_r1710718113`に書かれているとおり、印をつける方法はデメリットが大きい
5-
func hasCycle(head *ListNode) bool {
5+
func hasCycleFloyd(head *ListNode) bool {
66
slow, fast := head, head
77
for fast != nil && fast.Next != nil {
88
slow, fast = slow.Next, fast.Next.Next
@@ -12,3 +12,16 @@ func hasCycle(head *ListNode) bool {
1212
}
1313
return false
1414
}
15+
16+
func hasCycleMap(head *ListNode) bool {
17+
seen := make(map[*ListNode]struct{})
18+
node := head
19+
for node != nil {
20+
if _, ok := seen[node]; ok {
21+
return true
22+
}
23+
seen[node] = struct{}{}
24+
node = node.Next
25+
}
26+
return false
27+
}

0 commit comments

Comments
 (0)