leetcode 141. 环形链表

题解

通过快慢指针进行判断,如果有环则会相遇

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
fast, slow := head, head
for slow != nil && fast != nil {
slow = slow.Next
if fast.Next == nil {
return false
}
fast = fast.Next.Next
if slow == fast {
return true
}
}
if slow != fast {
return false
}
return true
}