Python recursive method


  • 1
    J
    # 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
            """
            dummyNode = ListNode(0)
            self.helper(l1, l2, 0, dummyNode)
            return dummyNode.next
            
        
        def helper(self, l1, l2 , carry, result):
            if l1 == None and carry == 0:
                result.next = l2
                return
            if l2 == None and carry == 0:
                result.next = l1
                return
            
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            
            sum = x + y + carry
            
            digit = sum % 10
            carry = sum / 10
            
            result.next = ListNode(digit)
            
            self.helper(l1.next if l1 else None, l2.next if l2 else None, carry, result.next)
    

Log in to reply
 

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