XOR Linked List – Reversal of a List

• Last Updated : 28 Oct, 2021

Examples:

Input: 4 <–> 7 <–> 9 <–> 7
Output: 7 <–> 9 <–> 7 <–> 4
Explanation:
Reversing the linked list modifies the XOR linked list to 7 <–> 9 <–> 7 <–> 4.

Input: 2 <-> 5 <-> 7 <-> 4
Output: 4 <-> 7 <-> 5 <-> 2
Explanation:
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:

1. Initialize a pointer variable, say curr, to pointto the current node being traversed.
2. Store the current head pointer in the curr variable.
3. If curr is equal to NULL, then return NULL.
4. Otherwise, traverse upto the last node and make it the head of the XOR linked list.

Below is the implementation of the above approach:

C

Output:

XOR linked list: 40 30 20 10
Reversed XOR linked list: 10 20 30 40

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :