Remove Nth Node From End of List Problem Solution

Remove Nth Node From End of List Problem: Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example :

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

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;
}


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment