使用快慢指针,让快指针先走n步,然后让快慢指针同时往后走,快指针到达末尾的时候,慢指针指向的即为倒数第n个结点。
为解决只有一个结点的情况,在开头增加一个结点。
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
head = ListNode(next=head)
slow, quick = head, head
for _ in range(n):
quick = quick.next
while quick.next:
slow = slow.next
quick = quick.next
slow.next = slow.next.next
return head.next