In this Leetcode Remove Nth Node From End of List problem solution we have given the head of a linked list, remove the nth node from the end of the list and return its head.

Leetcode Remove Nth Node From End of List problem solution


Problem solution in Python.

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:        
        slow = fast = head
        
        for i in range(n):
            fast = fast.next 
            
        if not fast:
            return head.next 
        
        while fast and fast.next:
            slow = slow.next 
            fast = fast.next 
        
        slow.next = slow.next.next 
        return head



Problem solution in Java.

public ListNode removeNthFromEnd(ListNode head, int n) {
    if( head == null )
        return null;
    ListNode fakeHead = new ListNode(-1);
    fakeHead.next = head;
    
    ListNode prev = fakeHead, slow = head;
    ListNode fast = head;
    for(int i = 1; i < n; i++)
        fast = fast.next;
    while(fast.next != null) {
        fast = fast.next;
        prev = slow;
        slow = slow.next;
    }
    prev.next = slow.next;
    return fakeHead.next;
}


Problem solution in C++.

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {

        //checking basic  conditions
        if(head==NULL)return head;
        if(n==0)return head;

        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* prev = NULL;

        while(n!=0){
            fast = fast->next;
            n--;
        }

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

        if(prev==NULL){
            ListNode* newHead = slow->next;
            delete slow;
            return newHead;
        }

        prev->next = slow->next;
        delete slow;
        return head;
    }
};


Problem solution in C.

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) 
{
    struct ListNode* current;
    current = head;
    int count = 0;
    
    while(current != NULL)
    {
        current = current->next;
        count++;
    }
    
    current = head;
    if(count==n)
        return current->next;
    
    count = count-n-1;
    while(count--)
    {
        current = current->next;
    }
    
    current->next = current->next->next;
    
    return head;
}