Leetcode 2: Add Two Numbers

Leetcode 2: Add Two Numbers

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

Analysis

It is a easy one. Pay attention to the carry-over.

Solution

Python codes

# 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
        """
        
        if l1 == None:
            return l2
        elif l2 == None:
            return l1
        
        head = None
        addup = 0
        
        while l1 != None and l2 != None:
            tv = (l1.val + l2.val + addup) % 10
            addup = (l1.val + l2.val + addup) // 10
            tl = ListNode(tv)
            
            if head == None:
                head = tl
                pl = tl
            else:
                pl.next = tl
                pl = tl
            
            l1 = l1.next
            l2 = l2.next
        
        while l1 != None:
            tv = (l1.val + addup) % 10
            addup = (l1.val + addup) // 10
            tl = ListNode(tv)
            pl.next = tl
            pl = tl
            l1 = l1.next
            
        while l2 != None:
            tv = (l2.val + addup) % 10
            addup = (l2.val + addup) // 10
            tl = ListNode(tv)
            pl.next = tl
            pl = tl
            l2 = l2.next
            
        if addup > 0:
            tl = ListNode(addup)
            pl.next = tl
            
        return head
posted @ 2016-01-14 12:30  luckysimple  阅读(130)  评论(0编辑  收藏  举报