XOR linked lists are basically efficient version of linked list which store addresses of previous and next nodes to implement Doubly Linked List using only single pointer. I was wondering if it's possible to implement the in Java, since it doesn't have pointers. In C this could be done by
/* Insert a node at the begining of the XORed linked list and makes the
newly inserted node as head */
void insert(struct node **head_ref, int data)
{
// Allocate memory for new node
struct node *new_node = (struct node *) malloc (sizeof (struct node));
new_node->data = data;
/* Since new node is being inserted at the begining, npx of new node
will always be XOR of current head and NULL */
new_node->npx = XOR(*head_ref, NULL);
/* If linked list is not empty, then npx of current head node will be XOR
of new node and node next to current head */
if (*head_ref != NULL)
{
// *(head_ref)->npx is XOR of NULL and next. So if we do XOR of
// it with NULL, we get next
struct node* next = XOR((*head_ref)->npx, NULL);
(*head_ref)->npx = XOR(new_node, next);
}
// Change head
*head_ref = new_node;
}
Is it possible to create a doubly linked list using only one pointer with every node. (B) Yes, possible by storing XOR of addresses of previous and next nodes.
To traverse the list, we need to get a pointer to the next node at every point. We can get the address of next node by keeping track of the current node and previous node. If we do XOR of curr->npx and prev, we get the address of next node. Note that the XOR of pointers is not defined by the C/C++ standard.
This memory efficient Doubly Linked List is called XOR Linked List or Memory Efficient as the list uses bitwise XOR operation to save space for one address. In the XOR linked list, instead of storing actual memory addresses, every node stores the XOR of addresses of previous and next nodes.
A doubly linked list is also a collection of nodes. Each node here consists of a data part and two pointers. One pointer points to the previous node while the second pointer points to the next node.
No, you can't do this in Java at all -- you cannot get the address of an object or compute a reference to an object from other values. This allows the garbage collector to move objects around without interfering with the program.
It's also a really bad idea in C++.
If you're worried about the memory overhead in a linked list, you can store multiple items per node. If a node has prev, next, and items[16] references, and you always make sure your nodes are at least half full, then it will use less memory than an XOR list on average.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With