Add Two Numbers
Example
Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
carry = 0
dummy = ListNode(0)
tail = dummy
while l1 and l2:
sum = l1.val + carry + l2.val
node = ListNode(sum % 10)
carry = sum / 10
tail.next = node
tail = node
l1 = l1.next
l2 = l2.next
while l1:
sum = l1.val + carry
node = ListNode(sum % 10)
carry = sum / 10
tail.next = node
tail = node
l1 = l1.next
while l2:
sum = l2.val + carry
node = ListNode(sum % 10)
carry = sum / 10
tail.next = node
tail = node
l2 = l2.next
if carry == 1:
node = ListNode(1)
tail.next = node
return dummy.nextLast updated