【题目】
【代码】
【方法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