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