1 vote
173 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 )
{
}
else
if ( nCurrentElement - NthNode > 0)
{
pNthNode = pNthNode ->pNext;
}
}
if (pNthNode )
{
return pNthNode;
}
else
return NULL;
}
0

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 = 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

1
339 views
To reverse a Singly Linked List is the below is correct code? (or) need to change Struct node *reverse(struct node *start) { Struct node *prev,*ptr,*next; prev=NULL; ptr=start; while(ptr!=NULL) { next=ptr->link; ptr->link=prev; prev=ptr; ptr=next; } start=prev; return start; Plz tell me, is here all link updating correctly?
1 vote
Consider an unrolled linked list with $n$ elements.This list stores multiple elements in each node. What is the worst case time complexity to find the $k^{th}$ element if the number of nodes and the number of elements in each node are equal? $A)O(n)$ $B)O(\sqrt n)$ $C)O(nlogn)$ $D)O(n^{2})$