Wednesday, April 20, 2022

C programming - Remove Nth Node From End of Singly Link List

Remove Nth Node From End of List

/**
 * Definition for singly-linked list.
*/
struct ListNode {
   int val;
   struct ListNode *next;
};

struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
    struct ListNode *f0 = head;
    struct ListNode *f1 = head;
    struct ListNode *f2 = head;
    struct ListNode *temp = head;
    int flag = 1;

    if((head ==  NULL) || (n < 0))
        return NULL;

    if(n == 0)
    {
        return head;
    }    
    else if(n == 1)
    {
        // if there is only one node in list
        if(head->next == NULL)
        {   
            free(head);
            return NULL;
        }    
        else
        {    
           while(f1->next != NULL)
           {
                f0 = f1;    
                f1 = f1->next;
           }    
        }
        free(f1);
        f0->next = NULL;
        return head;
    }
    
    n--;

    while(f2->next != NULL)
    {          
        if(n != 0)
        {        
           f2 = f2->next; 
           n--;
        }
        else
        {   
            f0 = f1; 
            f1 = f1->next;
            f2 = f2->next; 
            flag = 0;
        }
    } 
    if(flag != 0)
    {    
        temp = head->next;
        free(head);
    }
    else
    {
        f0->next = f1->next;
        temp = head;
        free(f1);
    }    
    return temp;
}

No comments:

Post a Comment