Simple Python solution


  • 1
    A
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
            
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            carry = 0
            head = previous = None
            while l1 or l2 or carry:
                s = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
                carry, val = s / 10, s % 10
                node = ListNode(val)
                if previous:
                    previous.next = node
                else: 
                    head = node
                previous = node
                l1 = l1.next if l1 else None
                l2 = l2.next if l2 else None
            return head
                
    

Log in to reply
 

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