• 1.首先将a、b链表反转
  • 2.定义变量label来记录是否存在当前链表a节点的值加链表b的值大于等于10的情况,若大于则下次遍历的链表节点和需要加1
  • 3.a、b两链表均相加完成,在判断label的值是否等于1,若等于则加到链表末尾
  • 4.再次反转链表即可得到结果
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def reverslist(self ,head:ListNode) -> ListNode:
        pre = testNode = ListNode(0)
        testNode.next = head
        cur = pre.next
        while cur.next:
            next=cur.next
            cur.next = next.next
            next.next = pre.next
            pre.next = next
        return testNode.next
        
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        if head1 == None:
            return head2
        if head2 ==None:
            return head1
        head1 = self.reverslist(head1)  #首先将链表1反转
        head2 = self.reverslist(head2)#首先将链表2反转
        label = 0
        result=head3 = ListNode(0)
        while head1 or head2:#当前while结束后,两个链表的值都相加完毕,后续只需要判断label等于1还是等于0
            ten = 0
            ten = ten +label
            if head1!=None:
                ten = ten+head1.val
                head1 = head1.next
            if head2!=None:
                ten = ten+head2.val
                head2 = head2.next
            label = 0     #进入循环后,先默认label=0,如果ten大于10,则进入下面的判断将其改为1
            if ten>=10:
                ten = ten -10
                label =1
            testNode = ListNode(ten)
            head3.next = testNode
            head3 = head3.next
        if label==1:             #当前面的while循环结束后,若此处label继续满足进位的标志,
                                  #则需要新建一个节点,将1插入链表末尾
            testNode = ListNode(label)
            head3.next = testNode
        return self.reverslist(result.next)  #最后返回反转后的结果
                    
                
                
            
            
                
                
                
                
                
                
        
        
        
        
            
        # write code here