Remove Nth Node From End of List

PROBLEM :

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

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
   
    struct ListNode *n1,*n2,*temp ;
    int i=1 ;
   
    n1=head ;
    n2=head ;
   
    while(i!=n)
    {
        n1=n1->next ;
        i++ ;
    }
    if(n1->next==NULL)
    {
        temp=head ;
        head=head->next ;
        free(temp) ;
       
        return head ;
    }
   
   
    i=1 ;
    n1=head ;
    n2=head->next ;
   
    while(i<n&&i!=n)
    {
        n2=n2->next ;
        i++ ;
    }
   
    while(n2->next!=NULL)
    {
        n1=n1->next ;
        n2=n2->next ;
    }
   
    temp=n1->next ;
    n1->next=temp->next ;
    free(temp) ;
   
    return head ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )