Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When writing recursion, it's usually best to think about the end case(s), then write the recursive case last. The other thing about recursion is its extremely useful to return the result. </p> <p>Yes, your solution is technically recursive, but I don't think the code works. At the line <code>current.next = head</code>, head is not defined, unless this code is in some class that you've not shown. Worse yet, it may infinite loop, because at the beginning of the function, <code>tail = p</code> and at the end your recursion is called with <code>tail</code>, thus an infinite loop. At best this will reverse a list of length 3, but not a list of any length.</p> <p>In Java, the recursive function often needs a "helper" function to get it started. First, assume the following node class:</p> <pre><code>public class Node{ public object data; public Node next; } </code></pre> <p>And given the problem statement, I'm assuming we're not allowed to play with the data pointers, just the next pointers. This code would be some other class than Node. </p> <pre><code>public Node recursiveReverse(Node p) { return helperReverse(p, null); } private Node helperReverse(Node p, Node previous) { if (p == null) { return p; } else if (p.next == null) { p.next == previous; return p; } else { Node next = p.next; p.next = previous; return helperReverse(next, p); } } </code></pre> <p>It gets even better if it's incorporated in the Node class.</p> <pre><code>public class Node{ public object data; public Node next; public Node reverse() { return reverse1(null); } private Node reverse1(Node previous) { if (next == null) { next == previous; return this; } else { Node other = next; next = previous; return reverse1(other, this); } } } </code></pre> <p>Enjoy!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload