2. Add Two Numbers(Linked List)

题目地址

题目描述:

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:

小学加法思路,判断是否需要进一,用left来做记录。用dummy来记录。(dummy其实只是一个node,然后把计算得到的node依次在其后记录,最终的dummy.next其实也是一个node)

代码:

def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    curr = dummy = ListNode(0)
    left = 0
    while l1 or l2 or left:
        (l1, num1) = (l1.next, l1.val) if l1 else (None, 0)
        (l2, num2) = (l2.next, l2.val) if l2 else (None, 0)
        left, num = divmod(num1 + num2 + left, 10)
        curr.next = ListNode(num)
        curr = curr.next
    return dummy.next

思路其实很简单,只是对Linked List有所认识就可以做出来。

你可能感兴趣的:(2. Add Two Numbers(Linked List))