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

Intersection Of Two Linked Lists Problem

LeetCode 160. Given the heads of two singly linked-lists headA...

Sort List Problem

LeetCode 148. Given the head of a linked list, return...

Reorder List Problem

LeetCode 143. You are given the head of a singly...

Linked List Cycle Problem

LeetCode 141. Given head, the head of a linked list,...

Linked List Cycle II Problem

LeetCode 142. Given the head of a linked list, return...

Insertion Sort List Problem

LeetCode 147. Given the head of a singly linked list,...