> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/19.-shan-chu-lian-biao-de-dao-shu-dinge-jie-dian.md).

# 19. 删除链表的倒数第N个节点

<https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/>

## **解法一：**

设两个快慢指针fast和slow，fast比slow往前走**n+1**步，然后slow和fast每次向前走1步，这样当fast走到尽头时，slow恰好指向**倒数第n+1**个结点。指针操作将n+1结点之后的结点（即倒数第n个）删去即可。

&#x20;边界条件：倒数第1个和倒数第n个（设链表长度为n）。对于第1个，1+1=2，可以到达。对于第n个，n+1>n，超出链表长度。这里用个技巧，在链表头部加一个辅助用的头结点，这样就能解决倒数第n（即正数第一个）的情况。

```python
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        Head = ListNode(0)
        Head.next = head
        fast = Head
        for _ in range(n+1):           
            fast = fast.next
        slow = Head
        while fast: 
            fast = fast.next
            slow = slow.next
        #此时slow指向倒数第n+1
        slow.next = slow.next.next    #删去倒数第n个
        return Head.next
```
