141.E 环形链表
Problem: 141. 环形链表
思路
快慢指针。慢指针指向head
,快指针指向head.next
,每次分别走1步和2步。
Code
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
slow, fast := head, head.Next
for fast != slow {
// 避免空指针
if fast == nil || fast.Next == nil {
return false
}
slow = slow.Next
fast = fast.Next.Next
}
return true
}
Last updated
Was this helpful?