So, I have as part of my lesson in Computer Programming to reverse a singly linked list of nodes, based on this algorithm
“Traversing the list sequentially, remove each node and insert it as the new first node.”
I was able to do this iteratively, but now my professor wants us to do this recursively.
I am trying my best to understand recursion, but its not working very well.
So, I changed my coding from iteratively to what I believe to be recursively
private void recursiveReverse2(Node p)
{
Node lead = p;
Node tail = p;
if (p == null)
{
return;
}
if (p.next == null)
{
return;
}
current = tail.next;
lead = current.next;
current.next = null;
tail.next = lead;
current.next = head;
head = current;
recursiveReverse2(tail);
}
public void reverse2()
{
toggle(); //swithces sort of list from ascending-descending
recursiveReverse2(head); //head initialized at start of class
}
Basically, I wanted to ask if what I have done actually is recursion. Because, the recursiveReverse2() does work, but I just don’t know if I have implemented recursion or not.
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.
Yes, your solution is technically recursive, but I don’t think the code works. At the line
current.next = head, 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,tail = pand at the end your recursion is called withtail, thus an infinite loop. At best this will reverse a list of length 3, but not a list of any length.In Java, the recursive function often needs a “helper” function to get it started. First, assume the following node class:
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.
It gets even better if it’s incorporated in the Node class.
Enjoy!