Python solution


  • 2
    H
    def addTwoNumbers(self, l1, l2):
            head = None
            tail = None
            carry = 0
            
            while l1 or l2 or carry:
                new_val = 0
                if l1:
                    new_val += l1.val
                    l1 = l1.next
                if l2:
                    new_val += l2.val
                    l2 = l2.next
                new_val += carry
                carry = 0
                
                if new_val >= 10:
                    carry = new_val // 10
                    new_val = new_val % 10
                
                if not head:
                    head = ListNode(new_val)
                    tail = head
                else:
                    tail.next = ListNode(new_val)
                    tail = tail.next
                
            return head
    

Log in to reply
 

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