# 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
#
# 进阶:你能尝试使用一趟扫描实现吗?
#
#
#
# 示例 1:
#
#
# 输入:head = [1,2,3,4,5], n = 2
# 输出:[1,2,3,5]
方法:双指针
# leetcode submit region begin(Prohibit modification and deletion) # 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: ListNode, n: int) -> ListNode: dummy = ListNode(0, head) # 哑节点指向头结点 first = head # 快指针指向头结点 second = dummy # 慢指针指向哑节点 # 快指针先走n for i in range(n): first = first.next # 直至快指针为空,到链表结尾 while first: first = first.next second = second.next # 慢指针的next指向删除节点的next节点 second.next = second.next.next # 返回头结点 return dummy.next # leetcode submit region end(Prohibit modification and deletion)