Python solution, short and simple


  • 18
    M
    # 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
            """
            ret = ListNode(0)
            cur = ret
            add = 0
            
            while l1 or l2 or add:
                val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + add
                add = val / 10
                cur.next = ListNode(val % 10)
                cur = cur.next
                l1 = l1.next if l1 else None
                l2 = l2.next if l2 else None
            
            return ret.next

  • 0
    M

    Why do ret and cur need to be separate variables? Does this have something to do with how python instantiates variables?


  • 0
    M

    ret is a dummy head, in case both l1 and l2 is null; cur is the new list's constructor; they are for different purpose :)


  • 1
    M

    got it! great solution :)


  • 0
    E

    @Mrsuyi thanks,


  • 0
    B

    @Mrsuyi I'm still a little confused on this. Could you explain it in a different manner ? Thanks


Log in to reply
 

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