In this problem, I need to find the nth to the last node data of a singly linked list.
In order to do so, one good way is to use recursion, since it is automatically put recursion part into stack and what we want is to implement LIFO.
So here it comes:
void findn(node* head){ if(head==NULL) return; //head = head->next; // if use it, output n-1th not nth findn(head->next); if(nn==1) pp = head; --nn; }
It is very important to fully understand recursion. A good example that I followed is from <Absolute C++, 4th>.
full code comes here, very useful to learn C++. But still lack of use of class...Need to learn it, as well as .h file.
Executing the program....
$demo10_ 9_ 8_ 7_ 6_ 5_ 4_ 3_ 2_ 1_ end solution1: 6 solution2: 6I can also have depth variable feed as input to findn() function but should use (depth==2) so as to get the 6th to the last as output instead of 5th. need more deep understanding of recursion: chaining;;;;
void findn(node* head, int depth){ if(head==NULL) return; findn(head->next, depth-1); if(depth==1) pp = head; //But the index is wrong //--depth; }Here is the not correct output: should get 6 instead of 5
Executing the program.... $demo 10_ 9_ 8_ 7_ 6_ 5_ 4_ 3_ 2_ 1_ end 5