LC-19
19. 删除链表的倒数第 N 个结点
思路基本直接出来,双指针,IndexFast 和 IndexSlow 中间相隔 N - 1, 这样 IndexFast 到了最后,IndexSlow 自然就是倒数第 N 个结点。
Java实现
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode IndexFast = head;
ListNode IndexSlow = dummy;
for (int i = 0; i < n; i++) {
IndexFast = IndexFast.next;
}
while (IndexFast != null) {
IndexFast = IndexFast.next;
IndexSlow = IndexSlow.next;
}
IndexSlow.next = IndexSlow.next.next;
ListNode ans = dummy.next;
return ans;
}
}
Python实现
# 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 = ListNode(0,head)
fast = head
slow = dummy
for i in range(n):
fast = fast.next
while fast != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
使用虚拟头节点的好处:
没有虚拟,需要判断头节点,并且处理头节点的代码逻辑与处理其它节点(非头节点)的代码逻辑特别相似,有方法使得代码更优美并且能避免对头节点的判断呢?
可以通过在头节点的前面增加虚拟头节点,这样头节点就跟其它节点一样了,
不需要单独拎出来考虑,
但是需要注意的是返回的时候,需要返回虚拟头节点的下一节点而不是虚拟头节点。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能