[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.
Interview Questions and Answers :: Broadcom Ltd

4. How to find the nth node in linklist from back.

Answer:

Use 2 pointers:-

pNthNode
pTemp

Both the nodes point to the HEAD of the list. pNthNode starts moving only after pTemp has moved n nodes forward. From there, both nodes move forward until pTemp reaches NULL.
pNthNode now points at the nth node from the end.



/*
Defining a function to find the nth node from the end.
*/
struct node * nthNodeFromEnd(struct node * head, int n)
{
// we need to find the nth node from the end.
struct node * pTemp = head;
struct node * pNthNode = head;

int nCurrentElement = 0;

int counter = 0;

while(counter != n)
{
pTemp = pTemp -> next;
counter++;
}

while(pTemp != NULL)
{
pNthNode = pNthNode -> next;
pTemp = pTemp -> next;
}

return pNthNode;
}

Post Your Answer Here:      Public      Private

Rate This: +1 -0
Report     

Post Your Reply Here:     

Report Error

Report Error

Please Login First Click Here