Remove Nth Node From End of List Leetcode Solution

In this post, we are going to solve the Remove Nth Node From End of List Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Remove Nth Node From End of List Leetcode Solution
Remove Nth Node From End of List Leetcode Solution

Problem

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

Example 1:

Remove Nth Node From End of List Leetcode Solution
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

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

Example 3:

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

Now, lets see the leetcode solution of Remove Nth Node From End of List Leetcode Solution.

Remove Nth Node From End of List Leetcode Solution in Python

def removeNthFromEnd(self, head, n):
    fast = slow = dummy = ListNode(0)
    dummy.next = head
    for _ in xrange(n):
        fast = fast.next
    while fast and fast.next:
        fast = fast.next
        slow = slow.next
    slow.next = slow.next.next
    return dummy.next

Remove Nth Node From End of List Leetcode Solution in CPP

ListNode *removeNthFromEnd(ListNode *head, int n) 
{
    if (!head)
        return nullptr;

    ListNode new_head(-1);
    new_head.next = head;

    ListNode *slow = &new_head, *fast = &new_head;

    for (int i = 0; i < n; i++)
        fast = fast->next;

    while (fast->next) 
    {
        fast = fast->next;
        slow = slow->next;
    }

    ListNode *to_de_deleted = slow->next;
    slow->next = slow->next->next;
    
    delete to_be_deleted;

    return new_head.next;
}

Remove Nth Node From End of List Closest Leetcode Solution in 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) {
        ListNode slow = head;
        ListNode fast = head;
        while(n-- > 0) fast = fast.next;
        if(fast == null){
            ListNode rn = head;
            head = head.next;
            rn = null;
            return head;
        }
        while(fast.next != null){
            slow = slow.next;
            fast = fast.next;
        }
        
        ListNode rn = slow.next;
        slow.next = rn.next;
        rn = null;
        return head;
        
    }
}

Note: This problem Remove Nth Node From End of List is generated by Leetcode but the solution is provided by Chase2learn This tutorial is only for Educational and Learning purposes.

NEXT: Valid Parentheses Leetcode Solution

Sharing Is Caring