title: Finding the nth to last node in a single linked list using recursion
body: <p>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:</p>
  
  <pre><code>int findKthNode (node* head, int n){
      if(!head)
          return 1;
      int retval = findkthNode(head-&gt;next, n);
      if(retval==n)
          return head-&gt;val;
      return 1+retval;
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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.</p>