I know this question has been asked already but I would like to solve it using recursion. Each node in the list contains an integer value (int val). I would like to return the integer value, not just print it. I came up with the following:
int findKthNode (node* head, int n){
if(!head)
return 1;
int retval = findkthNode(head->next, n);
if(retval==n)
return head->val;
return 1+retval;
}
Once I reach the end of the list, I return 1. After that I add 1 to the previous return value until I reach the nth node from the end. At that point I return the int value at that node. There is one problem with this approach. I continue to add 1 until I return back to the first call. So if my list was 1,5,10,20,40,80,100, I would end up returning 85 for n=2, instead of 80 since I would add 1 five more times before returning. How would I fix this?
Also, I’m not sure if this is possible, but is there a way to return a pointer to the nth last node using recursion. I can’t see a way to do this with a singly linked list.
Don’t use the same variable for two different things, use two different variables. Pass an integer by reference to keep track of how many nodes from the end you are, and use the return for the result.