题解 | 链表相加(二)
链表相加(二)
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 inverse(self, head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
carry = 0
h1 = self.inverse(head1)
h2 = self.inverse(head2)
add = ListNode(0)
cur = add
while h1 or h2 or carry:
s = carry
if h1:
s+=h1.val
h1 = h1.next
if h2:
s+=h2.val
h2 = h2.next
carry, v = divmod(s, 10)
cur.next = ListNode(v)
cur = cur.next
return self.inverse(add.next)

查看11道真题和解析