Convert Singly Linked List to XOR Linked List - GeeksforGeeks

28 Mar, 2022
Prerequisite:  
XOR Linked List – A Memory Efficient Doubly Linked List | Set 1
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node’s address. Given a singly linked list, the task is to convert the given singly list to a XOR linked list. 
Approach: Since in XOR linked list each next pointer stores the XOR of prev and next nodes’s address. So the idea is to traverse the given singly linked list and keep track of the previous node in a pointer say prev.Now, while traversing the list, change the next pointer of every node as:  
current -> next = XOR(prev, current->next)
Printing the XOR linked list: While printing XOR linked list we have to find the exact address of the next node every time. As we have seen above that the next pointer of every node stores the XOR value of prev and next node’s address. Therefore, the next node’s address can be obtained by finding XOR of prev and next pointer of current node in the XOR linked list.So, to print the XOR linked list, traverse it by maintaining a prev pointer which stores the address of the previous node and to find the next node, calculate XOR of prev with next of current node.Below is the implementation of the above approach:  
CPP
Java
Python3
C#
Javascript
// C++ program to Convert a Singly Linked// List to XOR Linked List #include <bits/stdc++.h> using namespace std; // Linked List nodestruct Node {    int data;    struct Node* next;}; // Utility function to create new nodeNode* newNode(int data){    Node* temp = new Node;    temp->data = data;    temp->next = NULL;     return temp;} // Print singly linked list before conversionvoid print(Node* head){    while (head) {         // print current node        cout << head->data << " ";        head = head->next;    }     cout << endl;} // Function to find XORed value of// the node addressesNode* XOR(Node* a, Node* b){    return (Node*)((uintptr_t)(a) ^ (uintptr_t)(b));} // Function to convert singly linked// list to XOR linked listvoid convert(Node* head){    Node* curr = head;    Node* prev = NULL;    Node* next = curr->next;     while (curr) {         // store curr->next in next        next = curr->next;         // change curr->next to XOR of prev and next        curr->next = XOR(prev, next);         // prev will change to curr for next iteration        prev = curr;         // curr is now pointing to next for next iteration        curr = next;    }} // Function to print XORed linked listvoid printXOR(Node* head){    Node* curr = head;    Node* prev = NULL;     while (curr) {         // print current node        cout << curr->data << " ";         Node* temp = curr;         /* compute curr as prev^curr->next as           it is previously set as prev^curr->next so           this time curr would be prev^prev^curr->next           which is curr->next */        curr = XOR(prev, curr->next);         prev = temp;    }     cout << endl;} // Driver Codeint main(){    // Create following singly linked list    // 1->2->3->4    Node* head = newNode(1);    head->next = newNode(2);    head->next->next = newNode(3);    head->next->next->next = newNode(4);     cout << "Before Conversion : " << endl;    print(head);     convert(head);    cout << "After Conversion : " << endl;    printXOR(head);     return 0;}
// Java program to Convert a Singly Linked// List to XOR Linked Listimport java.io.*; // Linked List nodeclass Node{    int data;    Node next;        // Utility function to create new node    Node(int item)    {        data = item;        next = null;    }}class GFG{    public static Node root;       // Print singly linked list before conversion    static void print(Node head)    {        while (head != null)        {                       // print current node            System.out.print(head.data + " ");            head = head.next;        }        System.out.println();    }       // Function to find XORed value of    // the node addresses    static Node XOR(Node a, Node b)    {        return b;    }       // Function to convert singly linked    // list to XOR linked list    static void convert(Node head)    {        Node curr = head;        Node prev = null;        Node next = curr.next;                 while(curr != null)        {                       // store curr->next in next            next = curr.next;                         // change curr->next to XOR of prev and next            curr.next = XOR(prev, next);                         // prev will change to curr for next iteration            prev = curr;                         // curr is now pointing to next for next iteration            curr = next;        }    }       // Function to print XORed linked list    static void printXOR(Node head)    {        Node curr = head;        Node prev = null;        while(curr != null)        {                       // print current node            System.out.print(curr.data + " ");            Node temp = curr;                         /* compute curr as prev^curr->next as           it is previously set as prev^curr->next so           this time curr would be prev^prev^curr->next           which is curr->next */            curr = XOR(prev, curr.next);            prev = temp;        }        System.out.println();    }       // Driver Code    public static void main (String[] args)    {               // Create following singly linked list        // 1->2->3->4        GFG tree = new GFG();        tree.root = new Node(1);        tree.root.next = new Node(2);        tree.root.next.next = new Node(3);        tree.root.next.next.next = new Node(4);             System.out.println("Before Conversion : ");        print(root);        convert(root);        System.out.println("After Conversion : ");        printXOR(root);    }} // This code is contributed by avanitrachhadiya2155
# Python3 program to Convert a Singly Linked# List to XOR Linked List # Linked List nodeclass Node:    def __init__(self,d):        self.data = d        self.next = None # Print singly linked list before conversiondef printt(head):    while (head):         # print current node        print(head.data, end=" ")        head = head.next    print() # Function to find XORed value of# the node addressesdef XOR(a, b):    return b # Function to convert singly linked# list to XOR linked listdef convert(head):    curr = head    prev = None    next = curr.next     while (curr):         # store curr.next in next        next = curr.next         # change curr.next to XOR of prev and next        curr.next = XOR(prev, next)         # prev will change to curr for next iteration        prev = curr         # curr is now pointing to next for next iteration        curr = next # Function to print XORed linked listdef printXOR(head):    curr = head    prev = None     while (curr):         # print current node        print(curr.data, end=" ")         temp = curr         # /* compute curr as prev^curr.next as        #    it is previously set as prev^curr.next so        #    this time curr would be prev^prev^curr.next        #    which is curr.next */        curr = XOR(prev, curr.next)         prev = temp     print() # Driver Codeif __name__ == '__main__':         # Create following singly linked list    # 1.2.3.4    head = Node(1)    head.next = Node(2)    head.next.next = Node(3)    head.next.next.next = Node(4)     print("Before Conversion : ")    printt(head)     convert(head)    print("After Conversion : ")    printXOR(head) # This code is contributed by mohitkumar29
using System;class Node{    public int data;    public Node next;         // Utility function to create new node    public Node(int item)    {        data = item;        next = null;    }} public class GFG{    static Node root;       // Print singly linked list before conversion    static void print(Node head)    {        while (head != null)        {                        // print current node            Console.Write(head.data + " ");            head = head.next;        }        Console.WriteLine();    }       // Function to find XORed value of    // the node addresses    static Node XOR(Node a, Node b)    {        return b;    }         // Function to convert singly linked    // list to XOR linked list    static void convert(Node head)    {        Node curr = head;        Node prev = null;        Node next = curr.next;               while(curr != null)        {                        // store curr->next in next            next = curr.next;                          // change curr->next to XOR of prev and next            curr.next = XOR(prev, next);                          // prev will change to curr for next iteration            prev = curr;                          // curr is now pointing to next for next iteration            curr = next;        }    }         // Function to print XORed linked list    static void printXOR(Node head)    {        Node curr = head;        Node prev = null;        while(curr != null)        {                        // print current node            Console.Write(curr.data + " ");            Node temp = curr;                          /* compute curr as prev^curr->next as           it is previously set as prev^curr->next so           this time curr would be prev^prev^curr->next           which is curr->next */            curr = XOR(prev, curr.next);            prev = temp;        }        Console.WriteLine();    }         // Driver Code    static public void Main ()    {               // Create following singly linked list        // 1->2->3->4        GFG.root = new Node(1);        GFG.root.next = new Node(2);        GFG.root.next.next = new Node(3);        GFG.root.next.next.next = new Node(4);                      Console.WriteLine("Before Conversion : ");        print(root);        convert(root);        Console.WriteLine("After Conversion : ");        printXOR(root);    }} // This code is contributed by rag2127
<script>// javascript program to Convert a Singly Linked// List to XOR Linked List// Linked List nodeclass Node {     // Utility function to create new node    constructor(val) {        this.data = val;        this.next = null;    }}var root;     // Print singly linked list before conversion    function print( head) {        while (head != null) {             // print current node            document.write(head.data + " ");            head = head.next;        }        document.write("<br/>");    }     // Function to find XORed value of    // the node addresses    function XOR( a,  b) {        return b;    }     // Function to convert singly linked    // list to XOR linked list    function convert( head) {        var curr = head;        var prev = null;        var next = curr.next;         while (curr != null) {             // store curr->next in next            next = curr.next;             // change curr->next to XOR of prev and next            curr.next = XOR(prev, next);             // prev will change to curr for next iteration            prev = curr;             // curr is now pointing to next for next iteration            curr = next;        }    }     // Function to print XORed linked list    function printXOR( head) {        var curr = head;        var prev = null;        while (curr != null) {             // print current node            document.write(curr.data + " ");            var temp = curr;             /*             * compute curr as prev^curr->next as it is previously set as prev^curr->next so             * this time curr would be prev^prev^curr->next which is curr->next             */            curr = XOR(prev, curr.next);            prev = temp;        }        document.write();    }     // Driver Code              // Create following singly linked list        // 1->2->3->4             root = new Node(1);        root.next = new Node(2);        root.next.next = new Node(3);        root.next.next.next = new Node(4);        document.write("Before Conversion : <br/>");        print(root);        convert(root);        document.write("After Conversion : <br/>");        printXOR(root); // This code contributed by gauravrajput1</script>
Before Conversion : 
1 2 3 4 
After Conversion : 
1 2 3 4
 
Akanksha_Rai
mohit kumar 29
avanitrachhadiya2155
rag2127
GauravRajput1
sagar0719kumar
khushboogoyal499
as5853535
sumitgumber28
Bitwise-XOR
doubly linked list
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Program to implement Singly Linked List in C++ using class
Swap nodes in a linked list without swapping data
Priority Queue using Linked List
Circular Singly Linked List | Insertion
Real-time application of Data Structures
Insertion Sort for Singly Linked List