Share my simple Python code, O(n) time O(1)space


  • 0
    R
    class Solution:
    # @param two ListNodes
    # @return the intersected ListNode
    def getIntersectionNode(self, headA, headB):
        lenA, lenB = 0, 0
        p, q, r = headA, headB, None
        while p:
            lenA += 1
            p = p.next
        while q:
            lenB += 1
            q = q.next
        for i in range(lenA-lenB):
            headA = headA.next
        for i in range(lenB-lenA):
            headB = headB.next
        while 1:
            if headA == headB:
                r = headA
                break
            headA = headA.next
            headB = headB.next
        return r

Log in to reply
 

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