514 views
1 votes
1 votes

How does this code return Nth the node from the end of the linked list in one pass?

Node * GetNthNode ( Node* Head , int NthNode )
{
      Node * pNthNode = NULL;
      Node * pTempNode = NULL;
      int nCurrentElement = 0;
     
for ( pTempNode = Head; pTempNode != NULL; pTempNode = pTempNode->pNext )
      {
            nCurrentElement++;                 
            if ( nCurrentElement - NthNode == 0 )
            {
                  pNthNode = Head;
            }
            else
            if ( nCurrentElement - NthNode > 0)
            {
                  pNthNode = pNthNode ->pNext;
            }                            
      }
      if (pNthNode )
      {
            return pNthNode;
      }
      else
            return NULL;
}

1 Answer

0 votes
0 votes

 Size of linked list is not given here. Below is the generic logic

Distance from head to K and A to END is same.

Step 1 in the image describes the first if condition :

if (nCurrentElement - NthNode == 0 ) {
    pNthNode = Head;
}
//pNthNode = NewPointer

Step 2 in the image describes elseif condition :

else if ( nCurrentElement - NthNode > 0){
    pNthNode = pNthNode ->pNext;
}

By the end of for loop NewPointer is the Nth node from end.

edited by

Related questions

0 votes
0 votes
1 answer
1
Mrityudoot asked Feb 25
179 views
How can we find the highest element in a singly linked list in O(1)? We are free to use any extra space.