I'm trying to recursively reverse a singly linked list in Java and I learned from this code from Stanford. Could someone please help me translate the C/C++ code to java so that my recursiveReverse() will still be a void method?
Here's the C/C++ solution from Stanford:
void RecursiveReverse(struct node** headRef) {
struct node* first;
struct node* rest;
if (*headRef == NULL) return;
first = *headRef;
rest = first->next;
if (rest == NULL) return;
RecursiveReverse(&rest);
first->next->next = first;
first->next = NULL;
*headRef = rest;
}
Here's my attempt at the code translation:
public void recursiveReverse(Element<T> currElement) {
Element<T> first;
Element<T> rest;
if (currElement == null) return;
first = currElement;
rest = currElement.next;
if (rest == null) return;
recursiveReverse(rest);
first.next.next = first;
first.next = null;
head = rest;
}
I originally used "currElement = rest" as the last line but with that, when I started with 1,2,3,null, the output I got was 1, null
But after using head = rest (the linkedlist's original head), I now have 2,1,null.
Could someone please help me translate it correctly so I can get the output as 3,2,1,null? Any help will be much appreciated.
Thanks.