问题19:给定一个链表,删除链表的倒数第n
个节点,并且返回链表的头结点。
先思考另一道题:给定一个链表,输出链表的倒数第n
个节点。
用快慢指针,快指针先走n
步,然后慢指针和快指针同速搜索。当快指针指向链表末尾None
的时候,慢指针恰好指向链表倒数第n
个节点。下图以n=2
为例。
有了这个思考做基础,删除倒数第n
个节点就不难了,只需要让fast
指针提前停止一位,则slow
指针的停止位置是倒数第n+1
个节点,直接slow.next = slow.next.next
,就把倒数第n
个节点删除了。
完整代码:
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
if not head:
return head
fast, slow = head, head
for i in range(n):
if fast == None:
return None
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
运行结果: