链表 02. 找出环形链表的入环点

题目:给定一个链表的头节点  head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 None。    中等

方法一:哈希表  时间复杂度O(N)  空间复杂度O(N)

 

def detectCycle(head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None

        hash1 = set()

        while head:
            if head in hash1:
                return head
            hash1.add(head)
            head = head.next
        return None

方法二:双指针  时间复杂度O(N)  空间复杂度O(1)

第一个入环点为两个指针分别从头结点和快慢指针第一次相遇结点等步长行进的第一个交点。

def detectCycle(head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None

        slow = head
        fast = head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                cur = head
                while cur != slow:
                    cur = cur.next
                    slow = slow.next
                return cur
        return None

 

posted @ 2022-07-13 14:41  Liang-ml  阅读(14)  评论(0)    收藏  举报