I was reading about XOR linked list and one question came to my mind that Is it possible to have a circular XOR linked list?
It seems to me that even if we somehow build such a list, it would be impossible to traverse it given head node of the list. For e.g - Let the linked list contain 3 nodes: A, B and C.
|
v
A ---> B ---> C
A->xor = B ^ C
B->xor = A ^ C
C->xor = A ^ B
Since we are given head
of the list i.e A
in this case, we will not be able to either move forward or backward, as we have to know at-least one of the B
or C
in order to move. Since we cannot traverse it, we can't build it too.
Am I correct in what I am thinking? Or am I missing something?
Indeed you are right, it is impossible to traverse this list since we cannot retrieve any pointer value from the xor
link.
The minimal requirement for this list to become traversable is two pieces of information … for instance the pointer to the current node, and a pointer to the next (or previous) node. Then you can retrieve all the information from the xor
link.
In fact, this is what the Wikipedia article says anyway:
To start traversing the list in either direction from some point, you need the address of two consecutive items, not just one
This is still cheaper than storing two pointers for each node since we only need one link per node, plus two pointers for the current and next (or previous) node.