2025/2/25 【双指针】LeetCode19. 删除链表的倒数第N个结点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
1.非双指针方法
# 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, n): # 1.遍历一遍链表,得到链表长度 length = 0 p = head while p: length += 1 p = p.next # 2.1 特殊判定,要删除的点恰好是链表的头节点 if length == n: return head.next # 2.2 删除除了头节点之外的节点。 else: n = length - n cur = head pre = cur while cur and n != 0: n -= 1 pre = cur cur = cur.next pre.next = cur.next return head
2.快慢双指针方法
注意:这题的解法必须要有一个虚拟头节点。
# 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, n): # 创建一个虚拟节点,并将其下一个指针设置为链表的头部 dummy_head = ListNode(0, head) # 创建两个指针,慢指针和快指针,并将它们初始化为虚拟节点 slow = fast = dummy_head # 快指针比慢指针快 n+1 步,这样当fast指向链表末尾的时候,slow恰好指向要删除的节点的前一个节点 for i in range(n+1): fast = fast.next # 移动两个指针,直到快速指针到达链表的末尾 while fast: slow = slow.next fast = fast.next # 通过更新第 (n-1) 个节点的 next 指针删除第 n 个节点 slow.next = slow.next.next return dummy_head.next