Python O(n) time O(1) extra space except for output without reverse


  • 0
    Z
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            n1 = 1
            n2 = 1
            h1 = l1
            h2 = l2
            while h1.next is not None:
                n1+=1
                h1 = h1.next
            while h2.next is not None:
                n2+=1
                h2 = h2.next
            if n1 >= n2:
                p1 = l1
                pn1 = n1
                p2 = l2
                pn2 = n2
            else:
                p1 = l2
                pn1 = n2
                p2 = l1
                pn2 = n1
            ans = ListNode(0)
            wait = ans
            head = ans
            while p1 is not None:
                if pn1>pn2:
                    summation = p1.val+0
                    pn1 -= 1
                    p1=p1.next
                else:
                    summation = p1.val + p2.val
                    p1=p1.next
                    p2=p2.next
                if summation >= 10:
                    wait.val+=1
                    head.next=ListNode(summation-10)
                    while wait.next is not None:
                        wait = wait.next
                        if wait.val == 9:
                            wait.val = 0
                else:
                    head.next = ListNode(summation)
                    if summation<9:
                        wait = head.next
                head = head.next
                while wait.next is not None and wait.next.val<9:
                    wait=wait.next
            if ans.val==0:
                ans=ans.next
            return ans
            
    

Log in to reply
 

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