'How to understand head->next->next = head; for reverse single list by Recursion?
A signle link list, i want revese it by recursion. but i don't understand the meaning of this line head->next->next = head;.
why there need head->next->next?
struct Node{
int data;
Node* next;
};
Here is the implement code:
Node* reverseByRecursion(Node *head)
{
if(head == NULL || head->next == NULL)
return head;
Node *newHead = reverseByRecursion(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
Solution 1:[1]
Let me work with this list.
reverseByRecursion(node1)is called.- Neither
node1nornode1->nextisNULL, sonewHead = reverseByRecursion(head2);is called. - Neither
node2nornode2->nextisNULL, sonewHead = reverseByRecursion(head3);is called. head3->nextisNULL, sohead3is returned fromreverseByRecursion(head2).head = node2andhead->next = node3, sohead->next->next = head;will setnode3->nexttonode2.head->next = NULL;will setnode2->nexttoNULL. (image 2)newHead, which isnode3, is returned fromreverseByRecursion(head2).head = node1andhead->next = node2, sohead->next->next = head;will setnode2->nexttonode1.head->next = NULL;will setnode1->nexttoNULL. (image 3)newHead, which isnode3, is returned fromreverseByRecursion(node1).- Now the list is reversed with having
node3as the head.
Solution 2:[2]
Your base case says that if there are no more elements, then the current node becomes the head of the list.
The head->next->next = head line means that the next node is being reused with its pointer pointing backward (in the opposite direction as before). Since the node used to be the NEXT node after the current node, it becomes the PREVIOUS node before the current head, and its next pointer therefore ought to point to the current node ("head").
Solution 3:[3]
try to understand it this way, .next actually meant to change the arrow pointing to the next value. So
head.next.next = head
means adding an arrow from the next next position and point it back to head
Hope this is more intuitive to understand
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MikeCAT |
| Solution 2 | Robert Columbia |
| Solution 3 | Roll20 |



