【题目】
【代码】
【方法1】在head之前设置提供特殊节点mute用于保存head,mute的next指针指向head节点。

class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
mute=ListNode()
mute.val=-1
mute.next=head
fast=head
slow=head
pre=mute
while n:
n-=1
fast=fast.next
while fast:
pre=slow
slow=slow.next
fast=fast.next
pre.next=slow.next
return mute.next
【方法2】
没有头部多余的节点

class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
origin=head
del_p=head
pre=head
while n and head.next:
n-=1
head=head.next
if n!=0:
return origin.next
while head:
head=head.next
pre=del_p
del_p=del_p.next
pre.next=del_p.next
return origin
本文介绍两种方法实现删除链表中倒数第N个节点的问题。方法一通过增设哑节点简化操作;方法二则直接进行操作,无需额外的哑节点。这两种方法都有效地解决了问题,并提供了清晰的实现思路。

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



