4. How to find the nth node in linklist from back.
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;
}
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;
}
Report Error
Report Error
Please Login First Click Here