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

这题和Add Binary很像,只是一个使用linked list作为载体,一个是使用array作为载体。同样要注意的是进位的处理。有几种特殊情况要注意,一个是其中一个输入为None,另外是两个输入长度不等。注意当carry有值或者其中一个input有值时都需要再进行计算。另外一个需要注意的地方是,linked list需要维护结点之间的连接关系。但是在处理当前结点时除非对carry,input1的下一位,input2的下一位做判断,无法从当前结点确定的建立对下一个结点的连接。一个比较好的办法是在进行当前计算时,循环中有上一个计算结果的结点cur,本次的计算结果保存在 cur.next。也就是引入哑元素dummy,计算两个input的头结点时使用dummy作为上一个计算结果。代码如下:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if (not l1) and (not l2):
            return None
        dummy = ListNode(-1) 
        cur = dummy
        carry = 0 
        while l1 or l2 or carry :
            if l1:
                carry +=l1.val
                l1=l1.next
            if l2:
                carry +=l2.val
                l2=l2.next

            cur.next=ListNode(carry%10)
            cur=cur.next
            carry = carry/10
        return dummy.next
            

 

posted on 2016-04-23 20:44  Sheryl Wang  阅读(156)  评论(0编辑  收藏  举报

导航