给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
first=head
sec=head
index=0
#first向后移动n位
while index<n:
first=first.next
index+=1
#如果first为空 说明要删除的是第一位 直接返回第二位即可
if not first:
return head.next
#不然移动sec 直到first为空
while True:
if first.next==None:
break
sec=sec.next
first=first.next
first=sec.next.next
sec.next=first
return head

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



