2.Add Two Numbers Leetcode Python New season for 2016

1223 ワード

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


# 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
        """
        value_sum = 0
        dummy_head = head = ListNode(None)
        while l1 or l2:
            if l1:
                value_sum += l1.val
                l1 = l1.next
            if l2:
                value_sum += l2.val
                l2 = l2.next
            head.next = ListNode(value_sum % 10)
            head = head.next
            value_sum /= 10
        if value_sum == 1:
            head.next = ListNode(1)
        return dummy_head.next

traverse the whole tree and sum up the value in the node by order.
O(n) time and O(n) space