Node * FindNthFromBack(struct node *Head, int n)
{
struct node *ptr1, *ptr2; // we need 2 pointers
ptr1 = ptr2 = Head; // set the pointers to point to the list head initially
while(ptr1->link != NULL) // keep looping until we reach the tail (next will be NULL for the last node)
{
if(n > 0)
{
ptr1 = ptr1->link; //increment only the 1st pointer
n--;
}
else
{
ptr1 = ptr1->link; //increment both pointers
ptr2 = ptr2->link;
}
}
return ptr2; //now return the ptr2 which points to the nth node from the tail
}
Saturday, 9 July 2011
Finding Nth from Tail.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment