XOR Linked List – Reversal of a List
Given a XOR linked list, the task is to reverse the XOR linked list.
Input: 4 <–> 7 <–> 9 <–> 7
Output: 7 <–> 9 <–> 7 <–> 4
Reversing the linked list modifies the XOR linked list to 7 <–> 9 <–> 7 <–> 4.
Input: 2 <-> 5 <-> 7 <-> 4
Output: 4 <-> 7 <-> 5 <-> 2
Reversing the linked list modifies the XOR linked list to 4 <-> 7 <-> 5 <-> 2.
Approach: XOR linked listconsists of a single pointer, which is the only pointer needed to traverse the XOR linked list in both directions. Therefore, the idea to solve this problem is only by making the last node of the XOR linked list its Head Node. Follow the steps below to solve the problem:
- Initialize a pointer variable, say curr, to pointto the current node being traversed.
- Store the current head pointer in the curr variable.
- If curr is equal to NULL, then return NULL.
- Otherwise, traverse upto the last node and make it the head of the XOR linked list.
Below is the implementation of the above approach:
XOR linked list: 40 30 20 10 Reversed XOR linked list: 10 20 30 40
Time Complexity: O(N)
Auxiliary Space: O(1)