classSolution: defremoveNthFromEnd(self, head: ListNode, n: int) -> ListNode: p = head stack = [-1for i inrange(101)] # 使用列表模拟一个栈 count = 0# 计数
while p: stack[count] = p.val p = p.next count += 1
if count-n == 0: # 找到要删除的元素,是第一个元素 head = head.next return head p = head pre = p for i inrange(0,count): if count - n == i: # 找到删除的元素 # print(i,p.val,pre.val) pre.next = p.next return head else: pre = p # 保存当前的地址 p = p.next# p指向下一个地址 return head