📅  最后修改于: 2023-12-03 15:36:20.844000             🧑  作者: Mango
在编程过程中,我们常常需要对链表进行操作。本篇文章将介绍如何删除链表的最后第N个节点。
我们可以通过双指针法来解决此问题。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeNthFromEnd(head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
slow = fast = dummy
for i in range(n):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next