The Gateway to Computer Science Excellence
+1 vote
122 views

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;
}
in Programming by (19 points) | 122 views
0
format the code please :)

1 Answer

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.

by Veteran (57.2k points)
edited by

Related questions

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,306 answers
198,314 comments
105,010 users