The following function is trying to find the nth to last element of a singly linked list.
For example:
If the elements are
Here is the code using 2 pointer approach : ( source )
struct node
{
int data;
struct node *next;
}mynode;
mynode * nthNodeFrmEnd(mynode *head, int n /*pass 0 for last node*/)
{
mynode *ptr1,*ptr2;
int count;
if(!head)
{
return(NULL);
}
ptr1 = head;
ptr2 = head;
count = 0;
while(count < n)
{
count++;
if((ptr1=ptr1->next)==NULL)
{
//Length of the linked list less than n. Error.
return(NULL);
}
}
while((ptr1=ptr1->next)!=NULL)
{
ptr2=ptr2->next;
}
return(ptr2);
}
node* findNthNode (node* head, int find, int& found){
if(!head) {
found = 1;
return 0;
}
node* retval = findNthNode(head->next, find, found);
if(found==find)
retval = head;
found = found + 1;
return retval;
}