LeetCode 19: Remove Nth Node From End of List

LeetCode 19: Remove Nth Node From End of List

    • [1. Problem Link 🔗](#1. Problem Link 🔗)
    • [2. Solution Overview 🧭](#2. Solution Overview 🧭)
    • [3. Solution 1: Two Pointers with Dummy Node (Recommended)](#3. Solution 1: Two Pointers with Dummy Node (Recommended))
      • [3.1. Algorithm](#3.1. Algorithm)
      • [3.2. Important Points](#3.2. Important Points)
      • [3.3. Java Implementation](#3.3. Java Implementation)
      • [3.4. Time & Space Complexity](#3.4. Time & Space Complexity)
    • [4. Solution 2: Two Pass with Length Calculation](#4. Solution 2: Two Pass with Length Calculation)
      • [4.1. Algorithm思路](#4.1. Algorithm思路)
      • [4.2. Important Points](#4.2. Important Points)
      • [4.3. Java Implementation](#4.3. Java Implementation)
      • [4.4. Time & Space Complexity](#4.4. Time & Space Complexity)
    • [5. Solution 3: Recursive Approach](#5. Solution 3: Recursive Approach)
      • [5.1. Algorithm思路](#5.1. Algorithm思路)
      • [5.2. Important Points](#5.2. Important Points)
      • [5.3. Java Implementation](#5.3. Java Implementation)
      • [5.4. Time & Space Complexity](#5.4. Time & Space Complexity)
    • [6. Solution 4: Stack-based Approach](#6. Solution 4: Stack-based Approach)
      • [6.1. Algorithm思路](#6.1. Algorithm思路)
      • [6.2. Important Points](#6.2. Important Points)
      • [6.3. Java Implementation](#6.3. Java Implementation)
      • [6.4. Time & Space Complexity](#6.4. Time & Space Complexity)
    • [7. Solution 5: Two Pointers without Dummy Node](#7. Solution 5: Two Pointers without Dummy Node)
      • [7.1. Algorithm思路](#7.1. Algorithm思路)
      • [7.2. Important Points](#7.2. Important Points)
      • [7.3. Java Implementation](#7.3. Java Implementation)
      • [7.4. Time & Space Complexity](#7.4. Time & Space Complexity)
    • [8. Solution Comparison 📊](#8. Solution Comparison 📊)
    • [9. Summary 📝](#9. Summary 📝)

LeetCode 19: Remove Nth Node From End of List

2. Solution Overview 🧭

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

Example:

复制代码
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

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

Constraints:

  • The number of nodes in the list is sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Common approaches include:

  • Two Pass with Length Calculation: Calculate length first, then remove (L-n+1)th node
  • One Pass with Two Pointers: Use fast and slow pointers to find the nth node from end
  • Stack-based Approach: Use stack to track nodes (less efficient)

3. Solution 1: Two Pointers with Dummy Node (Recommended)

3.1. Algorithm

  • Use a dummy node to handle edge cases (like removing head)
  • Move fast pointer n steps ahead of slow pointer
  • Move both pointers until fast reaches the end
  • Slow pointer will be at (n+1)th node from end
  • Remove the next node of slow pointer

3.2. Important Points

  • Most efficient and elegant solution
  • Handles edge cases gracefully
  • One pass algorithm

3.3. Java Implementation

java 复制代码
/**
 * 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) {
        // Create dummy node to handle edge cases
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode slow = dummy;
        ListNode fast = dummy;
        
        // Move fast pointer n steps ahead
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        
        // Move both pointers until fast reaches the end
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        
        // Remove the nth node from end
        slow.next = slow.next.next;
        
        return dummy.next;
    }
}

3.4. Time & Space Complexity

  • Time Complexity: O(L) where L is the length of the list
  • Space Complexity: O(1)

4. Solution 2: Two Pass with Length Calculation

4.1. Algorithm思路

  • First pass: Calculate the length of the list
  • Calculate which node to remove (length - n + 1)
  • Second pass: Traverse to the node before the target and remove it

4.2. Important Points

  • Simple and intuitive
  • Easy to understand and implement
  • Two passes but still efficient

4.3. Java Implementation

java 复制代码
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Calculate length of the list
        int length = 0;
        ListNode current = head;
        while (current != null) {
            length++;
            current = current.next;
        }
        
        // If removing the head
        if (n == length) {
            return head.next;
        }
        
        // Find the node before the one to remove
        current = head;
        for (int i = 1; i < length - n; i++) {
            current = current.next;
        }
        
        // Remove the node
        current.next = current.next.next;
        
        return head;
    }
}

4.4. Time & Space Complexity

  • Time Complexity: O(L)
  • Space Complexity: O(1)

5. Solution 3: Recursive Approach

5.1. Algorithm思路

  • Use recursion to traverse to the end of the list
  • Use a counter to track the position from the end
  • When counter equals n, skip that node

5.2. Important Points

  • Elegant recursive solution
  • Uses O(L) stack space
  • Good for understanding recursion

5.3. Java Implementation

java 复制代码
class Solution {
    private int count = 0;
    
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // Use a dummy node to handle head removal
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        removeHelper(dummy, n);
        return dummy.next;
    }
    
    private void removeHelper(ListNode node, int n) {
        if (node == null) {
            return;
        }
        
        removeHelper(node.next, n);
        count++;
        
        // When we reach the nth node from end in backtracking
        if (count == n + 1) {
            node.next = node.next.next;
        }
    }
}

5.4. Time & Space Complexity

  • Time Complexity: O(L)
  • Space Complexity: O(L) for recursion stack

6. Solution 4: Stack-based Approach

6.1. Algorithm思路

  • Push all nodes onto a stack
  • Pop n nodes to reach the nth node from end
  • The next node in stack is the one before the target
  • Remove the target node

6.2. Important Points

  • Simple to understand
  • Uses O(L) extra space
  • Good for learning purposes

6.3. Java Implementation

java 复制代码
import java.util.Stack;

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        Stack<ListNode> stack = new Stack<>();
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;
        
        // Push all nodes onto stack
        while (current != null) {
            stack.push(current);
            current = current.next;
        }
        
        // Pop n nodes to find the node to remove
        for (int i = 0; i < n; i++) {
            stack.pop();
        }
        
        // The top of stack is the node before the target
        ListNode nodeBefore = stack.peek();
        nodeBefore.next = nodeBefore.next.next;
        
        return dummy.next;
    }
}

6.4. Time & Space Complexity

  • Time Complexity: O(L)
  • Space Complexity: O(L)

7. Solution 5: Two Pointers without Dummy Node

7.1. Algorithm思路

  • Similar to Solution 1 but without dummy node
  • Handle head removal as a special case
  • More complex edge case handling

7.2. Important Points

  • Saves one node of memory
  • More complex code
  • Good for understanding pointer manipulation

7.3. Java Implementation

java 复制代码
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = head;
        
        // Move fast pointer n steps ahead
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        
        // If fast is null, we're removing the head
        if (fast == null) {
            return head.next;
        }
        
        // Move both until fast reaches last node
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        
        // Remove the node
        slow.next = slow.next.next;
        
        return head;
    }
}

7.4. Time & Space Complexity

  • Time Complexity: O(L)
  • Space Complexity: O(1)

8. Solution Comparison 📊

Solution Time Complexity Space Complexity Advantages Disadvantages
Two Pointers with Dummy O(L) O(1) Elegant, handles edges well Uses one extra node
Two Pass with Length O(L) O(1) Simple, intuitive Two passes
Recursive O(L) O(L) Elegant, recursive thinking Stack overflow risk
Stack-based O(L) O(L) Easy to understand Extra space usage
Two Pointers without Dummy O(L) O(1) No extra node Complex edge handling

9. Summary 📝

  • Key Insight: The nth node from end is the (L-n+1)th node from beginning
  • Recommended Approach: Solution 1 (Two Pointers with Dummy Node) is most commonly used
  • Critical Technique: Using two pointers with n-step difference to find the target in one pass
  • Pattern Recognition: This is a classic two-pointer pattern for linked list problems

Why Two Pointers Work:

  • When fast pointer is n steps ahead, and both move at same speed
  • When fast reaches the end, slow will be at (L-n)th position
  • This allows us to remove the next node (which is the target)

The two pointers with dummy node approach is generally preferred for its elegance and robustness in handling edge cases.

相关推荐
爬山算法5 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
智驱力人工智能5 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
kfyty7256 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎6 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄6 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
忆~遂愿6 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
小韩学长yyds6 小时前
Java序列化避坑指南:明确这4种场景,再也不盲目实现Serializable
java·序列化
仟濹6 小时前
【Java基础】多态 | 打卡day2
java·开发语言
孞㐑¥6 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
Re.不晚6 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言