Python solution in O(n) time and use only O(1) memory


  • 0
    B
    class Solution(object):
        def getIntersectionNode(self, headA, headB):
            """
            :type head1, head1: ListNode
            :rtype: ListNode
            """
            if not headA or not headB:
                return None
            t2 = headB
            while t2.next:
                t2 = t2.next
            t2.next = headB
            dummy = ListNode(-1)
            dummy.next = headA
            fast = dummy
            slow = dummy
            flag = False
            while fast and fast.next:
                fast = fast.next.next
                slow = slow.next
                if fast == slow:
                    flag = True
                    break
            if not flag:
                dummy = None
                t2.next = None
                return None
            tmp = dummy
            while tmp != slow:
                tmp = tmp.next
                slow = slow.next
            dummy = None
            t2.next = None
            return tmp

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.