【算法】【线性表】【链表】Remove Nth Node From End of List 删除链表的倒数第N个节点
1 题目
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
2 解答
这里有一个巧妙的点就是 倒数第n个节点:
比如有10个节点,删除倒数第2个,双指针法
第一个指针先遍历 2个,然后第二个指针还是从头开始遍历,当第一个指针遍历到尾部时,第二个指针的下一个节点就是要被删除的节点,第二个指针跟第一个指针相差2个节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { // 参数边界考虑 if (head == null || n <= 0) { return head; } // 链表就一个元素 直接返回吧 if (head.next == null) { return null; } // 双指针法 // node先遍历 n个 ListNode node = head; for (int i = 0; i < n - 1; i++) { node = node.next; } // 加个头节点 // preNode 永远指向被删除节点的前一个节点 // 这个要理解 ListNode preNode = new ListNode(0); preNode.next = head; // 如果删除的是第一个节点 那么就不会进入while循环 while (node.next != null) { node = node.next; preNode = preNode.next; } ListNode delNode = preNode.next; preNode.next = delNode.next; // 如果删除的是第一个节点,就返回 preNode.next 否则就返回head return delNode == head ? preNode.next : head; } }
加油。
分类:
算法 / 链表
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了