For my Computer Science class, we are writing several different methods to reverse a singly linked list in Java. I cannot figure out the last way, which uses three helper methods, pointerToLast(Node n) which returns the tail node, nextToLast(Node n) which returns the second to last, and append(Node a, Node b) which links together the two nodes. The method is supposed to be recursive. Here's what I have so far:
public static ListNode reverse(ListNode head)
{
if(head == null)
return null;
if(head.getNext() == null)
return head;
ListNode r = pointerToLast(head);
nextToLast(head).setNext(null);
append(r, reverseLL(head));
return r;
}
I was trying to make head shorter and keep adding the last value, which didn't work.
Oh, I forgot to mention that we have our own ListNode class, which only has next and value as private data, getNext() and getValue() for accessors, and setNext() and setValue() for modifiers. So anything like "a.previous" doesn't help. I'm really confused, can anyone help me? I can't figure out the recursion, like how to add stuff on.