这个问题是将两个用链表存储的数,求和相加。数是反序存储在链表中的,即表头存储的是数字的最低位,表尾存储的是数字的最高位。那么相加其实可以借鉴我们小学的知识啦,刚好反序的存储已经帮我们对齐两个数了。分别从表头开始对每一位相加,如果加和大于等于10,则进位1,个位作为结果保存在该位的加和上,进位在高位加和时要参与进去;如果加和小于10,则进位为0,加和直接作为结果保存在该位的加和上。需要注意的是两个数的长度可能不一致,那么加到最后,最长的还是需要继续参与加和。笔者的处理方法是短的高位补零,强行一致长度。具体代码和结果如下,算法的时间复杂度是,空间复杂度是(笔者英文不是特好,但是代码注释还是尝试着使用英文,等某天意识到哪里错的时候就来更正,也欢迎批评指正):
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
rtype = ListNode(0)
# store the head of the return list(store the return number)
# in my case, I GET more than one node in the list,I will delete before return
current_node = rtype
# point the current node that we deal with now
carry = 0
# to store the carry
while l1 != None or l2 != None:
# before the longest one conducted, we should continue the loop
current_node.next = ListNode(0)
current_node = current_node.next
# create the new node
# add it to the list and current_node point to it
if l1!= None:
number1 = l1.val
l1 = l1.next
else:
number1 = 0
if l2 != None:
number2 = l2.val
l2 = l2.next
else:
number2 = 0
# process two number to the same length by adding zero to the short one
sum = number1 + number2 + carry
# add two number in the same digit with carry
# if the result is more than or equal to ten, set carry to 1 and the remainder to the result
# else set the sum to the result
if sum>=10:
carry =1
current_node.val = sum-10
else:
carry = 0
current_node.val = sum
# if the sum of high digit still carry 1, we can't ignore it
if carry == 1:
current_node.next = ListNode(1)
# before return the number, the head node in the list should be discarded
current_node = rtype
rtype =rtype.next
current_node.next = None
return rtype
本题由于感觉这个算是很直接很简便的算法了,暂时没有想到更多的提升。所以暂时只有这个版本。