题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
from operator import ne import re from pickle import NONE # 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, head1:ListNode): #采用头插法反转列表 newList = None cur = head1 while(cur): next = cur.next cur.next = newList newList = cur cur = next # 这里的意思是,newList他不知道是否为ListNode,因为如果不走循环,那么他就是None return newList def addInList(self , head1: ListNode, head2: ListNode) -> ListNode: # write code here newList1 = self.reverseList(head1) newList2 = self.reverseList(head2) carry = 0 p = newList1 q = newList2 resList = None if (newList1 is None and newList2 is None): return newList2 while(p or q or carry): value1 = p.val if p else 0 value2 = q.val if q else 0 total = value1 + value2 + carry carry = total // 10 value = total % 10 newNode = ListNode(value) newNode.next = resList resList = newNode if p: p = p.next if q: q = q.next return resList
出现的问题 1.在循环体用到head 2. 忘记指针移动 3.调用成员函数要用self. 4.指针移动的前提是指针存在 5.成员函数的使用