python-leetcode-删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
# 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 = ListNode(0, head)
first = dummy
second = dummy
# 让第一个指针先走 n+1 步
for _ in range(n + 1):
first = first.next
# 同时移动两个指针,直到第一个指针到达链表末尾
while first:
first = first.next
second = second.next
# 删除倒数第 n 个节点
second.next = second.next.next
# 返回头节点
return dummy.next