题目描述:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
好了,回家high了几天,你们的搬运工小tutu回来了。这个题目乍一看emmm,一次遍历就实现,有点困难,常规的做法是扫描一趟,得出链表的长度,然后二次扫描,计数,当到达len(linkeslist)-n的时候head.next=head.next.next完成删除操作。
一天中午睡午觉的时候,刚入睡的那一瞬间,我想,能不能遍历链表,然后存入list中,llist可以通过下标取数,list[-n]不就能取出来了嘛,呵呵呵呵,醒来看了一下题目,emmm,要我返回一个链表,自己想的办法,含着泪都得做下去。
然后,我们再遍历list,形成一个链表,脑子有坑,但我还是做下去了。而且,我还要把代码贴出来,让自己丢人。
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
list=[]
while head:
list.append(head.val)
head=head.next
t=len(list)-n#list中的下标
if n!=len(list):#如果不是删除的第一个元素
ll=ListNode(list[0])#第一个元素就作为头节点
i=1
s=ll
while i<=len(list)-1:#下面开始遍历了
if i!=t:
s.next=ListNode(list[i])
i+=1
s=s.next
else:
i+=1
else:#如果删除的是第一个元素
if len(list)==1:
return None
else:#那么后面就不用判断,直接形成链表
ll=ListNode(list[1])
i=2
s=ll
while i<=len(list)-1:
s.next=ListNode(list[i])
i+=1
s=s.next
return ll
这代码,我还不如,遍历两遍,一行简单的代码搞定,愁死人了,所以,我要去搬运了,别打扰我。
然后看到了说用两个指针,相隔一定的距离,后一个指针的位置捡钱一个指针的位置等于n,一个指针到了链表尾部,另一个指针的next就删除,好了,我还是自己尝试一下吧。
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first=second=head
if first.next==None:#如果只有一个元素,就返回空
return []
else:
for i in range(n):#先移动first指针,使之与second指针相差n
if first.next:#因为n可能等于链表的长度,而当n等于链表长度时,first就已经到表尾的后面一个
first=first.next
else:
i=i-1#如果是非正常跳出循环,i-1,有i来判断是否是正常跳出
break
if i<n-1: #如果非正常跳出,说明就是删除的头节点
return second.next
else:
while first.next:
first=first.next
second=second.next
second.next=second.next.next
return head
为了防止first移到表尾的后一位,真的累死了,
然后发现,emmm,别人在头节点前加了个节点,这样就不会超出链表的长度了,在下佩服。
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
addNode=ListNode(0)
addNode.next=head#在head前添加一个节点,防止first没有next
first=second=addNode
for i in range(n):
first=first.next
while first.next:
first=first.next
second=second.next
second.next=second.next.next#其他地方正常考虑
return addNode.next#最后输出不能输出head,因为head可能被删除了
一下午整了一条题目,心好累,能力有待提升。
本文介绍了一种高效的一次遍历算法,用于删除链表的倒数第N个节点。通过双指针技巧,避免了两次遍历的复杂度,实现了简洁优雅的解决方案。

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



