Some of the interesting ways to reverse a linked list in place
0
/
2643
Below is the code snippet
Reverse a linked list in place
NODE *result = NULL;
NODE *current = *head;
NODE *next;
while(current != NULL) {
next = current->link;
current->link = result;
result = current;
current = next;
}
*head = result; // assign the reverse list back to head node of the list
The result node stores the result (the reversed linked list). Current node points to the current node while traversing and this will be used as an iterator to loop through the linked list. While traversing, we first save the next node to current in a ptr , then we link current node to the result(reverse list marked by NULL value initially as seen). We then store the current node ptr in the result(reverse list) and then increment current node ptr to point to the next node.Eventually, I assign the reverse list back to the head (first node of the list so that the list is reversed in place).
Below is the pictorial representation for better understanding.
1->2->3->4->5->NULL
current = 1
result = NULL
1->NULL
2->1->NULL
3->2->1->NULL
4->3->2->1->NULL
5->4->3->2->1->NULL
Below is the complete code to create/insert/print and reverse a linked list (another approach) using C language
Program to create/insert print and reverse a linked list
ID provided is not a Gistpen repo.
Feel free to comment, if you have any doubts or queries.