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 = 
        if not fast:
        while fast and
            slow = 
            fast = 
        return head

Problem Solution In Java

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

Problem Solution In C++

class Solution {
    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;

            fast = fast->next;

            prev = slow;

            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;
    current = head;
        return current->next;
    count = count-n-1;
        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.
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment