持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天。
题目链接: leetcode.com/problems/re…
1. 题目介绍(从列表末尾删除第n个节点)
Given the head of a linked list, remove the nth node from the end of the list and return its head.
【Translate】: 给定一个链表的头,从链表末尾移除第n个节点并返回它的头。
【测试用例】:
【约束】:
2. 题解
快慢指针无疑是解决链表问题的利器。
2.1 快慢指针
TMS提供的题解。它可以使用指针完成一次性解决方案。快速移动一个指针--> 向前n+1个位置,以保持两个指针之间的 n 间隔,然后以相同的速度移动两者。最后,当快指针到达末尾时,慢指针将落后n+1位——正好是它能够跳过下一个节点的正确位置。
由于问题表明n是有效的,因此不必进行太多检查。否则,这将是必要的。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0); // 初始化一个节点值为0的空节点,最常用最正规写法
ListNode slow = start, fast = start; // 定义快慢指针
slow.next = head; // ==> start.next = head;
//Move fast in front so that the gap between slow and fast becomes n
for(int i=1; i<=n+1; i++) {
fast = fast.next; //
}
//Move fast to the end, maintaining the gap
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//Skip the desired node
slow.next = slow.next.next;
return start.next;
}
sgallivan提供的题解,精简版的快慢指针。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head, slow = head;
for (int i = 0; i < n; i++) fast = fast.next;
if (fast == null) return head.next;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
3. 可参考
[1] 删除链表元素详解版(Java)
[2] 计算链表的长度
[3] 【JAVA】删除链表中的节点