educative.io

Educative

What is head.next doing in the recursive solution?

In the recursive solution, I don’t understand what the
head.next.next = head;
head.next = null;
code is doing. it seems like either the function is not immutable, or else modifying the head wouldn’t have any effect?

At this point in the code, the head pointer is pointing to the current node, and the remaining list to the right of the current node has already been reversed.

In other words, the next pointer of the current node (i.e. head) is pointing to the last node in the reversed linked list. In order to completely reverse the linked list, we need to insert the current node at the end of the reversed linked list. This is being done in the line:

head.next.next = head;

Now that the list has been completely reversed, we need to change the next pointer of the last node to point to null. Since the last node in the reversed list is now the current node (i.e. head), this is being done in the next line:

head.next = null;
1 Like