There are 2 problems:
- you are not saving the new
head
once it is returned (when you reach the end of the list), so the returnedhead
is always going to be the one of the first stack of recursion, which is the original first node; - you are not assigning
node.next
tonull
on the first node, so it will never become the new tail of the list.
This is the corrected code:
public Node reverse(Node head) {
Node node = head;
if (node.next == null) {
head = node;
return head;
}
Node next = node.next;
// fix for problem 2, we transform the current node in the tail
node.next = null;
// fix for problem 1, head is now the tail node
head = reverse(next);
next.next = node;
return head;
}
solved Reverse a singly linked list in Java