[LeetCode] 19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:
Exapmle 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

Follow up: Could you do this in one pass?

移除链表倒数第N个节点。

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

思路

思路是在头结点之前(一般我们创建dummy节点的位置)创建两个节点分别叫做 slow 和 fast。先让 fast 前移 N + 1 个节点,这样使得 slow 和 fast 之间有 N + 1 个节点的距离。然后同时让 slow 和 fast 前移,直到 fast 遍历到链表尾部。此刻 slow 停下来的位置就是需要移除的节点之前的那个节点。为什么需要使 slow 和 fast 之间有 N + 1 个节点的距离是因为我们移除的是 slow.next 这个节点。可以参考这个动图帮助理解。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
ListNode slow = dummy;
ListNode fast = dummy;
dummy.next = head;
for (int i = 0; i <= n; i++) {
fast = fast.next;
// System.out.println(fast.val);
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
let dummy = new ListNode(0);
let slow = dummy;
let fast = dummy;
dummy.next = head;
for (let i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast !== null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
};

[LeetCode] 19. Remove Nth Node From End of List
https://shurui91.github.io/posts/2412012849.html
Author
Aaron Liu
Posted on
November 8, 2019
Licensed under