I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList
, containing simple nodes called ListNode
). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()
ListNode:
public class ListNode{
public String data;
public ListNode next;
}
Right now my reverse
function just calls a helper function that takes an argument to allow recursion.
public AddressList reverse(){
return new AddressList(this.reverse(this.head));
}
with my helper func having the signature of private ListNode reverse(ListNode current)
At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in c
that recursively reversed and converted it to Java code by hand and it worked, but had no understanding of it.
edit: Nevermind, I figured it out in the meantime.
private AddressList reverse(ListNode current, AddressList reversedList){
if(current == null) return reversedList;
reversedList.addToFront(current.getData());
return this.reverse(current.getNext(), reversedList);
}
While I'm here, does anyone see any problems with this route?