06 November 2015

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

This problem is marked as Medium.

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def addTwoNumbers(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         output = ListNode(0)
15         p = output
16         
17         while l1 or l2:
18             v1 = l1.val if l1 else 0
19             v2 = l2.val if l2 else 0
20             s = v1 + v2 + p.val
21             digit = s % 10
22             rem = s // 10
23             p.val = digit
24             l1 = l1.next if l1 else l1
25             l2 = l2.next if l2 else l2
26             if l1 or l2 or rem > 0:
27                 p.next = ListNode(rem)
28                 p = p.next
29         return output