Adding Two Numbers in LinkedList

# 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
        """
        head1, head2 = l1, l2
        head3 = None
        last = head3
        
        carry = 0
        
        while head1 and head2:
            dsum = carry + head1.val + head2.val
            carry = dsum // 10
            d = dsum % 10
            
            node = ListNode(d)
            if head3 is None:
                head3 = node
                last = node
            else:
                last.next = node
                last = node
            
            head1 = head1.next
            head2 = head2.next
        
        terminal = None
        if head1:
            terminal = head1
            
        if head2:
            terminal = head2
        
        while terminal:
            dsum = carry + terminal.val
            carry = dsum // 10
            d = dsum % 10
            
            node = ListNode(d)
            last.next = node
            last = node
            
            terminal = terminal.next
        
        if carry > 0:
            node = ListNode(carry)
            last.next = node
            last = node
            
        return head3

Reference

Written with StackEdit.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.