A simple way out would be..Use two pointers..*traverse and *nth_positionboth initialised to null..While you traverse to the end of the list using *traverse,let *nth_position follow only after n iterations..So at all times, *nth_position will be n places behind *traverse..Continue till traverse reaches end of list..If list has less than n nodes, nth_position points to null.
Above answer was rated as good by the following members: yzesong, j_l_larson
RE: Find nth node from end of a singly linked list
struct node{ int data; node* next;};// This function will return the point to the nth node from the end.// If the number of links is less the value n then it returns the start of the linked list// If the linked list has only one node then it returns the link to the end node// (which again is the start node for that linked list)node* findNthNodeFromEnd(node *end int n){ if(!end || n<0) return NULL; else if(n 0) return end; char *p; node *curr *prev end; int i 0; curr prev - 1; p (char*)curr; while(p ! 0) { if(curr->next prev) { ++i; if(i n) return curr; prev curr; } --p; curr (node*)p; } return prev;}The explanation for this one should be easily understandable i guess. If you have doubt mail me.
RE: Find nth node from end of a singly linked list
A simple way out would be..Use two pointers..*traverse and *nth_positionboth initialised to null..While you traverse to the end of the list using *traverse let *nth_position follow only after n iterations..So at all times *nth_position will be n places behind *traverse..Continue till traverse reaches end of list..If list has less than n nodes nth_position points to null.