力扣刷题-链表-环形链表

具体题目与思路见:https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E6%80%9D%E8%B7%AF
该文章详细介绍了如何寻找环入口点,以及数学原理。

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        # fast, slow = head # 快慢指针初始化为 头节点
        fast = ListNode()
        slow = ListNode()
        fast = head
        slow = head
        while fast and fast.next: # 是 fast and fast.next
            fast = fast.next.next
            slow = slow.next
            # 当快慢指针相遇
            if fast == slow: # 相遇就要开始找入环点 为什么相遇?说明一定有环 所以这里第一步可以用来判断是否有环
                index1 = fast
                index2 = head
                while index1 != index2:
                    index1 = index1.next
                    index2 = index2.next
                return index1
        return None

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