Find nth node from last of a singly linked list. You need to take care all the possible cases.
(there could be cycle in the list)
//Declare three global variables:
Boolean found=false;
Node requiredNthNode=null;
Int nodeCount=0;
//Now write a recurrsive method Process(Node)
void Process(Node node)
{
if(node->next)
Process(node->next)
nodeCount++;
if(nodeCount==N) //where N is the count from last
{
found=true;
requiredNthNode=node;
}
}
//Now the Actual Method
Node FindNthNode(head)
{
Process(head);
if(found)
return requiredNthNode;
else
return NULL;
}
Last edited by arif4123; 30th April 2011 at 14:55.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks