Description
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例 1:
输入: 7->1->6->null, 5->9->2->null
输出: 2->1->9->null
样例解释: 617 + 295 = 912, 912 转换成链表: 2->1->9->null
思路
用一个变量(carry)来记录该位的和,初始值为0,carry = carry + l1 + l2,
该位是carry % 10,carry = carry /10
解
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
carry = 0
rst = ListNode(0)
head = rst
while True:
if l1 != None:
carry += l1.val
l1 = l1.next
if l2 != None:
carry += l2.val
l2 = l2.next
head.val = carry % 10
carry = int(carry/10)
if l1 != None or l2 != None or carry != 0:
head.next = ListNode(0)
head = head.next
else:
break
return rst
注意事项:
python3 要用int()来把除法的结果cast成整形 不然默认是double
分析
时间复杂度 O(N+M), N, M为l1和l2的长度
空间复杂度 O(1)