![]() |
VOOZH | about |
Given pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes.
For Example:
Input:
Output:
Let's look at the ways to achieve this in Python:
The idea is to reverse the links of all nodes using threepointers:
Starting from the first node, initialize curr with the head of linked list and next with the next node of curr. Update the next pointer of currwith prev. Finally, move the three pointer by updating prevwith currand currwith next.
Given Linked List 85 15 4 20 Reversed Linked List 20 4 15 85
Explanation:
The idea is to reach the last node of the linked list using recursion then start reversing the linked list from the last node.
Given linked list 1 2 3 4 5 Reverse linked list 5 4 3 2 1
Explanation:
Please refer Reverse a linked list for more details!