![]() |
VOOZH | about |
Given pointer to the head node of a linked list, the task is to reverse the linked list.
Examples:
Input : Head of following linked list 1->2->3->4->NULL Output : Linked list should be changed to, 4->3->2->1->NULL Input : Head of following linked list 1->2->3->4->5->NULL Output : Linked list should be changed to, 5->4->3->2->1->NULL
We have seen how to reverse a linked list in article Reverse a linked list. In iterative method we had used 3 pointers prev, cur and next. Below is an interesting approach that uses only two pointers. The idea is to use XOR to swap pointers.
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85
Time Complexity: O(n)
Auxiliary Space: O(1) since using space for prev and next
Alternate Solution :
Given linked list 85 15 4 20 Reversed Linked list 20 4 15 85
Time Complexity : O(n)
Auxiliary Space: O(1)
Thanks to Abhay Yadav for suggesting this approach.