【题目】
【代码】
【方法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
版权声明:本文为kz_java原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。