19\. Remove Nth Node From End of List

# 19. Remove Nth Node From End of List (opens new window)

# Description

Difficulty: Medium

Related Topics: Linked List (opens new window), Two Pointers (opens new window)

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]
1
2

Example 2:

Input: head = [1], n = 1
Output: []
1
2

Example 3:

Input: head = [1,2], n = 1
Output: [1]
1
2

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?

# Solution

Language: JavaScript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 * 1.暴力求解
 * 找到列表的长度
 * 删除从列表开头数起第(L-n+1)个节点
 * 
 * 2.快慢指针法
 * 关键字:倒数第N个
 * 模式识别:
 * 涉及链表的特殊位置,考虑快慢指针
 * 要删除链表节点,找到它的前驱
 */
var removeNthFromEnd = function(head, n) {
    const dummy = new ListNode(-1, head);
    let [slow, fast] = [dummy, dummy];
    
    for (let i = 0; i <= n; i++) 
        fast = fast.next;
    
    while (fast) {
        slow = slow.next;
        fast = fast.next;
    }
    
    slow.next = slow.next.next;
    
    return dummy.next;
};
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
27
28
29
30
31
32
33
34
35
36
37
上次更新: 2022/7/13 上午11:21:17