今天是代码随想录的第一天!Keep on!
做了142.环形链表II这道题目
力扣链接:https://leetcode.cn/problems/linked-list-cycle-ii/
代码随想录链接
讲解链接
这道题目主要问题在于:
两个数学推导挺有意思的;
解题的Python代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# If there is a cycle, the slow and fast pointers will eventually meet
if slow == fast:
# Move one of the pointers back to the start of the list
temp = head
while temp != fast:
temp = temp.next
fast = fast.next
return temp
# If there is no cycle, return None
return None```