LintCode:167. 链表求和

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
您在真实的面试中是否遇到过这个题?
样例

给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null

"""
Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
"""


class Solution:
    """
    @param: l1: the first list
    @param: l2: the second list
    @return: the sum list of l1 and l2 
    """
    def addLists(self, l1, l2):
        # write your code here
        if l1 is None and l2 is None:
            return None
        
        cur1 = l1.next
        cur2 = l2.next
        head = ListNode((l1.val + l2.val)%10)
        cur = head
        
        carry = (l1.val + l2.val) // 10
        #当其中一条链表为空的时候,为该链表添加一个值为0的节点
        #直到两条都为None,这种方式会修改原先的列表.
        while cur1 is not None or cur2 is not None:
            if cur1 is None:cur1 = ListNode(0)
            if cur2 is None:cur2 = ListNode(0)
            
            val = cur1.val + cur2.val + carry
            carry = val // 10
            cur.next = ListNode(val%10)
            
            cur = cur.next
            cur1 = cur1.next
            cur2 = cur2.next
            
        if carry != 0:
            cur.next = ListNode(carry)
        
        return head

你可能感兴趣的:(LintCode:167. 链表求和)