Is it possible to implement XOR LinkedList in Java(DLL with single pointer)

6.7k Views Asked by At

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;
}
1

There are 1 best solutions below

3
Matt Timmermans On

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.