题目链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/

核心思路:双指针+虚拟头节点

  1. 定义slow 和 fast指针 ,分别初始化为虚拟头节点

  2. fast指针先走 N+1步,再同时移动slow指针,此时等fast走到末尾,slow正好指向被删除节点的前一个节点

#
# @lc app=leetcode.cn id=19 lang=python3
#
# [19] 删除链表的倒数第 N 个结点
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy_head = ListNode(0,head)

        slow = fast = dummy_head

        for i in range(n+1):
            fast = fast.next
        
        while fast:
            fast = fast.next
            slow = slow.next


        #被删除节点
        slow.next = slow.next.next
        
        return dummy_head.next
        
# @lc code=end