Skip to content
Rain Hu's Workspace
Go back

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

Rain Hu

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:
remove_ex1

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Straight Forward

ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode* dummy = new ListNode(-1, head);
    int len = 0;
    ListNode* curr = head;
    while (curr) {                      // 先求鏈表長度
        len++;
        curr = curr->next;
    }
    len -= n;                           // 求欲刪除的節點往頭算是第幾個節點
    curr = dummy;
    while (len--) curr = curr->next;    // 移動至該節點前
    curr->next = curr->next->next;      // 移除節點
    return dummy->next;
}

2. Two Pointers

ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode* dummy = new ListNode(-1, head);
    ListNode* fast = dummy, *slow = dummy;
    while (n--) fast = fast->next;      // 前指針先走 n 步
    while (fast->next) {                // 前後指針等速移動至前指針走完
        fast = fast->next;
        slow = slow->next;
    }
    slow->next = slow->next->next;      // 移除節點
    return dummy->next;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1016. Binary String With Substrings Representing 1 To N
Next
[LeetCode] 1293. Shortest Path in a Grid with Obstacles Elimination