top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Sudo code to delete 'n' th node of a linked list from the last ?

+4 votes
508 views
Sudo code to delete 'n' th node of a linked list from the last ?
posted Nov 1, 2014 by Ganesh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Have two pointers – slow and fast and initialize both pointers to head. First move fast pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now slow pointer is the target node to be deleted and just delete it.

Sample Code

void DeleteNthFromLast(struct node **head, int n)
{
  struct node *slow = *head;
  struct node *fast = *head;
  struct node *pre=null; // to store the previpus pointer of the node to be deleted

  int count = 0;
  if(*head != NULL)
  {
     while( count < n )
     {
        if(fast == NULL)
        {
           printf("%d is greater than the no. of nodes in list", n);
           return;
        }
        fast = fast->next;
        count++;
     } 

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

     // Now we got the slow pointer which is the target node lets delete it
     if (pre == null)
     {
         // first node to be deleted so head will change
         *head = (*head)->next;
         free (slow);
     }
     else
     {
         pre->next = slow->next;
         free (slow);
     }

  }
}
answer Nov 2, 2014 by Salil Agrawal
Similar Questions
+3 votes

How to delete the node that given as argument in single linked list?
Is there any system call to get prev pointer ?

Note: Here the goal is to delete the address not the node's value

+2 votes

How to find the median of simple linked list and add a node after it? C program would be helpful?

+2 votes

I am looking for sample code which can impress an interviewer.

...