题目链接 | 142. 环形链表 II |
---|---|
思路 | 快慢指针-经典应用:相遇后,移动head 及slow 直至相遇 |
题解链接 | 没想明白?一个视频讲透!含数学推导(Python/Java/C++/Go/JS) |
关键点 | while fast and fast.next: ... && while head != slow: ... |
时间复杂度 | \(O(n)\) |
空间复杂度 | \(O(1)\) |
代码实现:
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast is slow:
while slow is not head:
slow = slow.next
head = head.next
return head
return None
标签:II,head,slow,142,fast,next,链表,while
From: https://www.cnblogs.com/WrRan/p/18409128