给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
双指针法思路:见题解https://leetcode.cn/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
由于我们需要找到倒数第 n 个节点,因此我们可以使用两个指针fast 和 slow 同时对链表进行遍历,并且 fast 比slow 超前 n 个节点。
当 fast 遍历到链表的末尾时,slow 就恰好处于倒数第 n 个节点。
具体地,初始时 slow和fast 均指向头节点。我们首先使用 fast 对链表进行遍历,遍历的次数为 n。
此时,fast 和slow 之间间隔了 n-1 个节点,即 fast比slow 超前了 n 个节点。
在这之后,我们同时使用 fast和slow对链表进行遍历。
当 fast 遍历到链表的末尾(即 fast 为空指针)时,slow恰好指向倒数第 n个节点。
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: dummy_head = ListNode() dummy_head.next = head slow, fast = dummy_head, dummy_head while (n!=0): #fast先往前走n步 fast = fast.next n -= 1 # fast 和 slow 一起往前走 while(fast.next != None): slow = slow.next fast = fast.next # 当fast 走到结尾后,slow的下一个节点为倒数第N个节点 slow.next = slow.next.next # 删除节点 # 返回头节点 return dummy_head.next
浙公网安备 33010602011771号