141. 环形链表
解法一: 哈希表
func hasCycle(head *ListNode) bool {
set := map[*ListNode]bool{}
cur := head
for cur != nil {
if has := set[cur]; has {
return true
} else {
set[cur] = true
}
cur = cur.Next
}
return false
}
解法二: 快慢指针
- 若链表为空或者链表只有一个节点,说明链表无环,返回false,若不符合
- 初始化慢指针slow和快指针fast都为head
- slow指针走一步,fast指针走两步,若slow指针和fast指针相遇则说明有环
func hasCycle(head *ListNode) bool {
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
return true
}
}
return false
}
142. 环形链表 II
哈希表解法
func detectCycle(head *ListNode) *ListNode {
set := map[*ListNode]bool{}
for head != nil {
if has :=set[head]; has {
return head
}
set[head] = true
head = head.Next
}
return nil
}
进阶: 你是否可以使用 O(1)
空间解决此题?
快慢指针
基于 141. 环形链表 的解法,直观地来说就是当快慢指针相遇时,让其中任一个指针指向头节点,然后让它俩以相同速度前进,再次相遇时所在的节点位置就是环开始的位置。
想知道背后的原理,去看代码随想录的题解吧
func detectCycle(head *ListNode) *ListNode {
fast, slow := head, head
for fast != nil && fast.Next != nil {
slow = slow.Next
fast = fast.Next.Next
if slow == fast {
for head != slow{
head = head.Next
slow = slow.Next
}
return slow
}
}
return nil
}