Sunday, August 17, 2008

Return Nth the node from the end of the singly-linked list

NODE* FindNthNodeFromEnd(NODE *pHead, int nValue)
{
//Validate input
if ( (NULL == pHead) || (1 > nValue) )
return NULL;

NODE *pLead = pHead; //Move lead pointer to Nth node

int ii = 0;

for (; ii < nValue; ii++)
{
pLead = pLead->pNext;

if (NULL == pLead)
break;
}

if (NULL == pLead)
{
if ( (nValue-1) == ii)
{
return pHead; //head node is the nth node from the end-of-list
}
else
{
return NULL; //the list is smaller than N nodes
}
}

NODE *pFollow = pHead; //Follow pointer follows from a distance of N nodes

//Move both pointers until pLead reaches end-of-list
while (pLead)
{
pLead = pLead->pNext;
pFollow = pFollow->pNext;
}

return pFollow;
}

0 comments: