代码随想录算法训练营第一天 |142.环形链表II

今天是代码随想录的第一天!Keep on!

做了142.环形链表II这道题目
力扣链接:https://leetcode.cn/problems/linked-list-cycle-ii/
代码随想录链接
讲解链接

这道题目主要问题在于:

  1. 判断链表是否环
  2. 如果有环,如何找到这个环的入口

两个数学推导挺有意思的;

解题的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```

你可能感兴趣的:(算法,链表,数据结构)