GFG App
Open App
Browser
Continue

# XOR Linked List – Reversal of a List

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++

 `// C++ program for the above approach` `#include` `using` `namespace` `std;`   `// Structure of a node` `// in XOR linked list` `struct` `Node` `{`   `    ``// Stores data value` `    ``// of a node` `    ``int` `data;`   `    ``// Stores XOR of previous` `    ``// pointer and next pointer` `    ``Node* nxp;` `};`   `// Function to find the XOR of two nodes` `Node* XOR(Node* a, Node* b)` `{` `    ``return` `(Node*)((``uintptr_t``)(a) ^ (``uintptr_t``)(b));` `}`   `// Function to insert a node with` `// given value at beginning position` `Node* insert(Node** head, ``int` `value)` `{`   `    ``// If XOR linked list is empty` `    ``if` `(*head == NULL)` `    ``{`   `        ``// Initialize a new Node` `        ``Node* node` `            ``= ``new` `Node();`   `        ``// Stores data value in` `        ``// the node` `        ``node->data = value;`   `        ``// Stores XOR of previous` `        ``// and next pointer` `        ``node->nxp = XOR(NULL, NULL);`   `        ``// Update pointer of head node` `        ``*head = node;` `    ``}`   `    ``// If the XOR linked list` `    ``// is not empty` `    ``else` `    ``{`   `        ``// Stores the address` `        ``// of current node` `        ``Node* curr = *head;`   `        ``// Stores the address` `        ``// of previous node` `        ``Node* prev = NULL;`   `        ``// Initialize a new Node` `        ``Node* node` `            ``= ``new` `Node();`   `        ``// Update curr node address` `        ``curr->nxp = XOR(node, XOR(NULL, curr->nxp));`   `        ``// Update new node address` `        ``node->nxp = XOR(NULL, curr);`   `        ``// Update head` `        ``*head = node;`   `        ``// Update data value of` `        ``// current node` `        ``node->data = value;` `    ``}` `    ``return` `*head;` `}`   `// Function to print elements of` `// the XOR Linked List` `void` `printList(Node** head)` `{`   `    ``// Stores XOR pointer` `    ``// in current node` `    ``Node* curr = *head;`   `    ``// Stores XOR pointer of` `    ``// in previous Node` `    ``Node* prev = NULL;`   `    ``// Stores XOR pointer of` `    ``// in next node` `    ``Node* next;`   `    ``// Traverse XOR linked list` `    ``while` `(curr != NULL)` `    ``{`   `        ``// Print current node` `        ``cout<data<<``" "``;`   `        ``// Forward traversal` `        ``next = XOR(prev, curr->nxp);`   `        ``// Update prev` `        ``prev = curr;`   `        ``// Update curr` `        ``curr = next;` `    ``}` `    ``cout << endl;` `}`   `// Function to reverse the XOR linked list` `Node* reverse(Node** head)` `{`   `    ``// Stores XOR pointer` `    ``// in current node` `    ``Node* curr = *head;` `    ``if` `(curr == NULL)` `        ``return` `NULL;` `    ``else` `    ``{`   `        ``// Stores XOR pointer of` `        ``// in previous Node` `        ``Node* prev = NULL;`   `        ``// Stores XOR pointer of` `        ``// in next node` `        ``Node* next;` `        ``while` `(XOR(prev, curr->nxp) != NULL)` `        ``{`   `            ``// Forward traversal` `            ``next = XOR(prev, curr->nxp);`   `            ``// Update prev` `            ``prev = curr;`   `            ``// Update curr` `            ``curr = next;` `        ``}`   `        ``// Update the head pointer` `        ``*head = curr;` `        ``return` `*head;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``/* Create following XOR Linked List` `    ``head-->40<-->30<-->20<-->10 */` `    ``Node* head = NULL;` `    ``insert(&head, 10);` `    ``insert(&head, 20);` `    ``insert(&head, 30);` `    ``insert(&head, 40);`   `    ``/* Reverse the XOR Linked List to give` `    ``head-->10<-->20<-->30<-->40 */` `    ``cout << ``"XOR linked list: "``;` `    ``printList(&head);` `    ``reverse(&head);` `    ``cout << ``"Reversed XOR linked list: "``;` `    ``printList(&head);`   `    ``return` `0;` `}`   `// This code is contributed by rutvik_56.`

## C

 `// C program for the above approach`   `#include ` `#include ` `#include `   `// Structure of a node` `// in XOR linked list` `struct` `Node {`   `    ``// Stores data value` `    ``// of a node` `    ``int` `data;`   `    ``// Stores XOR of previous` `    ``// pointer and next pointer` `    ``struct` `Node* nxp;` `};`   `// Function to find the XOR of two nodes` `struct` `Node* XOR(``struct` `Node* a, ``struct` `Node* b)` `{` `    ``return` `(``struct` `Node*)((``uintptr_t``)(a) ^ (``uintptr_t``)(b));` `}`   `// Function to insert a node with` `// given value at beginning position` `struct` `Node* insert(``struct` `Node** head, ``int` `value)` `{`   `    ``// If XOR linked list is empty` `    ``if` `(*head == NULL) {`   `        ``// Initialize a new Node` `        ``struct` `Node* node` `            ``= (``struct` `Node*)``malloc``(``sizeof``(``struct` `Node));`   `        ``// Stores data value in` `        ``// the node` `        ``node->data = value;`   `        ``// Stores XOR of previous` `        ``// and next pointer` `        ``node->nxp = XOR(NULL, NULL);`   `        ``// Update pointer of head node` `        ``*head = node;` `    ``}`   `    ``// If the XOR linked list` `    ``// is not empty` `    ``else` `{`   `        ``// Stores the address` `        ``// of current node` `        ``struct` `Node* curr = *head;`   `        ``// Stores the address` `        ``// of previous node` `        ``struct` `Node* prev = NULL;`   `        ``// Initialize a new Node` `        ``struct` `Node* node` `            ``= (``struct` `Node*)``malloc``(``sizeof``(``struct` `Node));`   `        ``// Update curr node address` `        ``curr->nxp = XOR(node, XOR(NULL, curr->nxp));`   `        ``// Update new node address` `        ``node->nxp = XOR(NULL, curr);`   `        ``// Update head` `        ``*head = node;`   `        ``// Update data value of` `        ``// current node` `        ``node->data = value;` `    ``}` `    ``return` `*head;` `}`   `// Function to print elements of` `// the XOR Linked List` `void` `printList(``struct` `Node** head)` `{`   `    ``// Stores XOR pointer` `    ``// in current node` `    ``struct` `Node* curr = *head;`   `    ``// Stores XOR pointer of` `    ``// in previous Node` `    ``struct` `Node* prev = NULL;`   `    ``// Stores XOR pointer of` `    ``// in next node` `    ``struct` `Node* next;`   `    ``// Traverse XOR linked list` `    ``while` `(curr != NULL) {`   `        ``// Print current node` `        ``printf``(``"%d "``, curr->data);`   `        ``// Forward traversal` `        ``next = XOR(prev, curr->nxp);`   `        ``// Update prev` `        ``prev = curr;`   `        ``// Update curr` `        ``curr = next;` `    ``}` `    ``printf``(``"\n"``);` `}`   `// Function to reverse the XOR linked list` `struct` `Node* reverse(``struct` `Node** head)` `{`   `    ``// Stores XOR pointer` `    ``// in current node` `    ``struct` `Node* curr = *head;` `    ``if` `(curr == NULL)` `        ``return` `NULL;` `    ``else` `{`   `        ``// Stores XOR pointer of` `        ``// in previous Node` `        ``struct` `Node* prev = NULL;`   `        ``// Stores XOR pointer of` `        ``// in next node` `        ``struct` `Node* next;` `        ``while` `(XOR(prev, curr->nxp) != NULL) {`   `            ``// Forward traversal` `            ``next = XOR(prev, curr->nxp);`   `            ``// Update prev` `            ``prev = curr;`   `            ``// Update curr` `            ``curr = next;` `        ``}`   `        ``// Update the head pointer` `        ``*head = curr;` `        ``return` `*head;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``/* Create following XOR Linked List` `    ``head-->40<-->30<-->20<-->10 */` `    ``struct` `Node* head = NULL;` `    ``insert(&head, 10);` `    ``insert(&head, 20);` `    ``insert(&head, 30);` `    ``insert(&head, 40);`   `    ``/* Reverse the XOR Linked List to give` `    ``head-->10<-->20<-->30<-->40 */` `    ``printf``(``"XOR linked list: "``);` `    ``printList(&head);` `    ``reverse(&head);` `    ``printf``(``"Reversed XOR linked list: "``);` `    ``printList(&head);`   `    ``return` `(0);` `}`

## Python3

 `# Python program for the above approach` `import` `ctypes`     `# Structure of a node in XOR linked list` `class` `Node:` `    `  `    ``def` `__init__(``self``, value):` `        ``self``.value ``=` `value` `        ``self``.npx ``=` `0`     `# create linked list class` `class` `XorLinkedList:` ` `  `    ``# constructor` `    ``def` `__init__(``self``):` `        ``self``.head ``=` `None` `        ``self``.tail ``=` `None` `        ``self``.__nodes ``=` `[]` `        `  `    `  `    ``# Function to insert a node with given value at given position` `    ``def` `insert(``self``, value):` `        `  `        ``# Initialize a new Node` `        ``node ``=` `Node(value)` `        `  `        ``# Check If XOR linked list is empty` `        ``if` `self``.head ``is` `None``:` `            `  `            ``# Update pointer of head node` `            ``self``.head ``=` `node` `            `  `            ``# Update pointer of tail node` `            ``self``.tail ``=` `node` `            `  `        ``else``:` `            `  `            ``# Update curr node address` `            ``self``.head.npx ``=` `id``(node) ^ ``self``.head.npx` `            `  `            ``# Update new node address` `            ``node.npx ``=` `id``(``self``.head)` `            `  `            ``# Update head` `            ``self``.head ``=` `node` `            `  `        ``# push node` `        ``self``.__nodes.append(node)` `        `  `    `  `    ``# Function to print elements of the XOR Linked List` `    ``def` `printList(``self``):` ` `  `        `  `        ``if` `self``.head !``=` `None``:` `            ``prev_id ``=` `0` `            ``node ``=` `self``.head` `            ``next_id ``=` `1` `            ``print``(node.value, end``=``' '``)` `            `  `            ``# Traverse XOR linked list` `            ``while` `next_id:` `                `  `                ``# Forward traversal` `                ``next_id ``=` `prev_id ^ node.npx` `                `  `                ``if` `next_id:` `                    `  `                    ``# Update prev` `                    ``prev_id ``=` `id``(node)` `                    `  `                    ``# Update curr` `                    ``node ``=` `self``.__type_cast(next_id)` `                    `  `                    ``# Print current node` `                    ``print``(node.value, end``=``' '``)` `                ``else``:` `                    ``return`   `                `  `    ``# method to check if the linked list is empty or not` `    ``def` `isEmpty(``self``):` `        ``if` `self``.head ``is` `None``:` `            ``return` `True` `        ``return` `False` `    `  `    ``# method to return a new instance of type` `    ``def` `__type_cast(``self``, ``id``):` `        ``return` `ctypes.cast(``id``, ctypes.py_object).value` `    `  `    `  `    ``# Function to reverse the XOR linked list` `    ``def` `reverse(``self``):` ` `  `        ``# Print Values is reverse order.` ` `  `        ``if` `self``.head !``=` `None``:` `        `  `            ``# Stores XOR pointer of` `            ``# in previous Node` `            ``prev_id ``=` `0` `            ``node ``=` `self``.tail` `            `  `            ``# Stores XOR pointer of` `            ``# in next node` `            ``next_id ``=` `1` `            `  `            ``print``(node.value, end``=``' '``)` `            `  `            ``while` `next_id:` `                `  `                ``# Forward traversal` `                ``next_id ``=` `prev_id ^ node.npx` `                ``if` `next_id:` `                    `  `                    ``# Update prev` `                    ``prev_id ``=` `id``(node)` `                    `  `                    ``# Update curr` `                    ``node ``=` `self``.__type_cast(next_id)` `                    ``print``(node.value, end``=``' '``)` `                ``else``:` `                    ``return` `                    `    `# Create following XOR Linked List` `# head-->40<-->30<-->20<-->10 ` `head ``=` `XorLinkedList()` `head.insert(``10``)` `head.insert(``20``)` `head.insert(``30``)` `head.insert(``40``)`     `# Reverse the XOR Linked List to give` `# head-->10<-->20<-->30<-->40 ` `print``(``"XOR linked list: "``, end ``=` `"")` `head.printList()`   `print``()` `print``(``"Reversed XOR linked list: "``, end ``=` `"")` `head.reverse()`   `# This code is contributed by Nidhi goel.`

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