Remove Nth Node From End of List Problem


Description

LeetCode Problem 19.

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

Example 1:

1
2
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

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

Example 3:

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


Sample C++ Code

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
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == NULL) 
            return NULL;
        ListNode* first = head;
        ListNode* second = new ListNode;
        second->next = head;
        
        int i = 1;
        while (first != NULL) {
            if (i > n) {
                second = second->next;
            }
            first = first->next;
            i ++;
        }
        if (second->next == head)
            head = head->next;
        else if (n > 1)
            second->next = second->next->next;
        else 
            second->next = NULL;
        return head;
        
    }
};




Related Posts

Flatten Binary Tree To Linked List Problem

LeetCode 114. Given the root of a binary tree, flatten...

Remove Duplicates from Sorted List Problem

LeetCode 83. Given the head of a sorted linked list,...

Rotate List Problem

LeetCode 61. Given the head of a linked list, rotate...

Reverse Nodes in k-Group Problem

LeetCode 25. Given a linked list, reverse the nodes of...

Swap Nodes in Pairs Problem

LeetCode 24. Given a linked list, swap every two adjacent...