Recursive python solution


  • 0
    G
    # 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
            """
            if l1 == None and l2 == None: return None;
            if l1 == None: l1 = ListNode(0);
            if l2 == None: l2 = ListNode(0);
                
            node = ListNode((l1.val + l2.val) % 10);
            if l1.val + l2.val > 9:
                if l1.next == None: l1.next = ListNode(0);
                if l2.next == None: l2.next = ListNode(0);
                l1.next.val += 1;
    
            node.next = self.addTwoNumbers(l1.next, l2.next);
            return node
    

Log in to reply
 

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