XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print the middle node ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Forward traversal ; Update prev ; Update curr ; If the length of the linked list is odd ; If the length of the linked list is even ; Driver Code ; Create following XOR Linked List head -- > 4 a > 7 a > 5
#include <bits/stdc++.h> NEW_LINE #include <inttypes.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = new Node ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = new Node ( ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } int printMiddle ( struct Node * * head , int len ) { int count = 0 ; struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; int middle = ( int ) len / 2 ; while ( count != middle ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } if ( len & 1 ) { cout << curr -> data << " ▁ " ; } else { cout << prev -> data << " ▁ " << curr -> data << " ▁ " ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 4 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; printMiddle ( & head , 3 ) ; return ( 0 ) ; }