--- tags: data_structure_python --- # Add Two Numbers (not finish) You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example:** ``` Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. ``` # Solution ### Solution 1: Iterative 1 (clean the code) ```python= # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # Time complexity: O(max(len(l1), len(l2))). # Space complexity: O(max(len(l1), len(l2))). p1, p2 = l1, l2 node = ListNode(None) pNode = node carry = 0 while p1 != None and p2 != None: x = p1.val + p2.val + carry if x > 9: carry = x // 10 x = x % 10 else: carry = 0 pNode.next = ListNode(x) pNode = pNode.next p1 = p1.next p2 = p2.next while p1 != None: # len(p1) > len(p2). x = p1.val + carry if x > 9: carry = x // 10 x = x % 10 else: carry = 0 pNode.next = ListNode(x) pNode = pNode.next p1 = p1.next while p2 != None: # len(p2) > len(p1). x = p2.val + carry if x > 9: carry = x // 10 x = x % 10 else: carry = 0 pNode.next = ListNode(x) pNode = pNode.next p2 = p2.next if carry != 0: pNode.next = ListNode(carry) return node.next ``` ### Solution 2: Iterative 2 (clean the code) ### Solution 3: Recursive