# 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 """ p = ListNode(-1) dummy = p val = 0 while l1 or l2 or val: if l1: val += l1.val l1 = l1.next if l2: val += l2.val l2 = l2.next p.next = ListNode(val % 10) val /= 10 p = p.next return dummy.next
First we make a dummy head and will append result next to it. There are three conditions that we need to keep processing the linkedlist:
- L1 has remained node
- L2 has remained node
- We have carry-out from previous computation
At each step, we make a new node with value of L1+ L2 (val % 10, then update val = val/10) and append the new node to the result list.