# 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, pHead:ListNode):
if pHead == None:
return None
cur = pHead
pre = None
while cur:
#断开链表,要记录后续一个
temp = cur.next
#当前的next指向前一个
cur.next = pre
#前一个更新为当前
pre = cur
#当前更新为刚刚记录的后一个
cur = temp
return pre
def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
#任意一个链表为空,返回另一个
if head1 == None:
return head2
if head2 == None:
return head1
#反转两个链表
head1 = self.ReverseList(head1)
head2 = self.ReverseList(head2)
#添加表头
res = ListNode(-1)
head = res
#进位符号
carry = 0
#只要某个链表还有或者进位还有
while head1 != None or head2 != None or carry != 0:
#链表不为空则取其值
val1 = 0 if head1 == None else head1.val
val2 = 0 if head2 == None else head2.val
#相加
temp = val1 + val2 + carry
#获取进位
carry = (int)(temp / 10)
temp %= 10
#添加元素
head.next = ListNode(temp)
head = head.next
#移动下一个
if head1:
head1 = head1.next
if head2:
head2 = head2.next
#结果反转回来
return self.ReverseList(res.next)