题目:
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.
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:
1、l1,l2都为真:l1.val + l2.val+carry
2、其中一个不为真:l1.val + 0 + carry
3、最后需要考虑二者都计算完毕后,检查carry
解法一:
单指针
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
L = ListNode(0)
p,carry = L,0
while l1 and l2:
tmp = ListNode(0)
p.next = tmp
p = p.next
p.val = l1.val + l2.val + carry
if p.val>9 :
p.val = p.val - 10
carry = 1
else:
carry = 0
l1,l2 = l1.next,l2.next
if l1:pre = l1
else: pre = l2
while pre:
tmp = ListNode(0)
p.next = tmp
p = p.next
p.val = pre.val + carry
if p.val>9 :
p.val = p.val - 10
carry = 1
else:
carry = 0
pre = pre.next
if carry:
tmp = ListNode(1)
p.next = tmp
return L.next
解法二:
两个变量分别临时存储l1.val and l2.val
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
L = ListNode(0)
head ,carry=L,0
while l1 or l2:
head.next = ListNode(0)
head = head.next
p = l1.val if l1 else 0
q = l2.val if l2 else 0
head.val = p+q+carry
if head.val>9:
head.val = head.val - 10
carry = 1
else:carry = 0
if l1:l1 = l1.next
if l2 :l2 = l2.next
if carry:
head.next = ListNode(1)
return L.next