给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if head is None:
return None
fast = slow = head
for i in range(n):
fast = fast.next
if fast is None:
return head.next
while fast.next is not None:
fast = fast.next
slow = slow.next
cur = slow.next
slow.next = cur.next
return head
本文介绍了一种算法,该算法可以删除给定链表中的倒数第N个节点,并返回修改后的链表的头结点。通过使用两个指针的方法,实现了高效的节点删除操作。
808

被折叠的 条评论
为什么被折叠?



