題目如下:
給定一個鏈表,返回鏈表開始入環(huán)的第一個節(jié)點。 如果鏈表無環(huán),則返回 null。
為了表示給定鏈表中的環(huán),我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環(huán)。
說明:不允許修改給定的鏈表。
進階:你是否可以不用額外空間解決此題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
使用一個額外的集合,這種方法比較簡單,就跟之前判斷有沒有環(huán)的那道題一樣。
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head:
return
s = {head}
while head.next:
head = head.next
if head in s:
return head
s.add(head)
使用快慢指針,不需要使用額外的空間。
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head or not head.next:
return
fast = head
slow = head
meet = None
# 快慢指針,快指針每次走兩步,慢指針每次走一步,如果有環(huán),肯定會相遇。(不要問我為什么)
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
meet = fast
break
# 沒有相遇,說明沒有環(huán)
if not meet:
return
# 兩個指針從鏈表開始位置和相遇的地方出發(fā),相遇的地方就是環(huán)開始的地方。
while meet != head:
meet = meet.next
head = head.next
return meet