141.环形链表
141.环形链表
题解
大水题,两种实现方式 思路:快慢指针,快慢指针相同则有环,证明:如果有环每走一步快慢指针距离会减 1
代码
package main
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle1(head *ListNode) bool {
mp := make(map[*ListNode]bool)
for head != nil {
if _, ok := mp[head]; ok {
return true
} else {
mp[head] = true
}
head = head.Next
}
return false
}
func hasCycle2(head *ListNode) bool {
if head == nil {
return false
}
fast, slow := head.Next, head
for fast != nil && fast.Next != nil {
if fast == slow {
return true
}
fast = fast.Next.Next
slow = slow.Next
}
return false
}
func main() {
}
|