search
Log In
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 )
            {
                  pNthNode = Head;
            }
            else
            if ( nCurrentElement - NthNode > 0)
            {
                  pNthNode = pNthNode ->pNext;
            }                            
      }
      if (pNthNode )
      {
            return pNthNode;
      }
      else
            return NULL;
}
in Programming 173 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.


edited by

Related questions

0 votes
1 answer
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?
asked Nov 19, 2018 in Programming srestha 339 views
1 vote
0 answers
2
410 views
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})$
asked Nov 18, 2018 in Programming Lakshman Patel RJIT 410 views
0 votes
0 answers
3
254 views
struct node* foo(struct node* a, struct node* b) { struct node* result, *rec; if(a==null) return b; else if(b==null) return a; else { rec=foo(a->next,b->next); result=a; a->next=b; b->next=rec; return result; } }
asked Sep 17, 2018 in Programming Vaishnavi01 254 views
0 votes
1 answer
4
676 views
What kind of linked list is best to answer question like “What is the item at position n?” a) Singly linked list b) Doubly linked list c) Circular linked list d) Array implementation of linked list
asked Aug 19, 2018 in Programming pradeepchaudhary 676 views
...