题解 | #链表相加(二)#反转-相加-进位
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head1 ListNode类
# @param head2 ListNode类
# @return ListNode类
#
class Solution:
# 链表不能从后往前,需要先反转链表,从前往后,先定义反转函数
def reverseList(self,head:ListNode):
if head==None:
return None
'''
cur,pre=head,None
while cur:
b=cur.next
cur.next=pre
pre=cur
cur=b
return pre'''
a,a.next,b=head,None,head.next # 初始化
while b: # 当b非空时
b,a,a.next=b.next,b,a # 遍历
return a
def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
# write code here
# 有至少一个空链表时
if not head1:
return head2
if not head2:
return head1
# 两个链表均不为空时
# 先反转
head1=self.reverseList(head1)
head2=self.reverseList(head2)
# 创建一个空链表
res=ListNode(-1)
head=res
# 填充空列表
carry=0 # 进位
while head1 or head2 or carry:
# 当n1 n2有1个不为空时(可能有一个为空)
val1=0 if not head1 else head1.val
val2=0 if not head2 else head2.val
a=val1+val2+carry
carry=(int)(a/10)
a=a%10 # 两值之和,除以10的余数
head.next=ListNode(a)
head=head.next
if head1:
head1=head1.next # 当n1为空时,不再移动
if head2:
head2=head2.next # 当n2为空时,不再移动
return self.reverseList(res.next)
