As noted in the article, this method is only useful if you have a pointer to the head or tail of a list; if you only have a pointer in the middle of the list, there’s nowhere to go.
About the method: consider the following linked list:
|0|A|0x01|<->|0x01|B|0x02|<->|0x02|C|0|
The list contains 3 nodes with values A, B, C and the prev / next pointer containing the hexadecimal values (addresses) of the previous / next element in the list. 0 is null
Instead of storing two pointers, we can use only one, as described in the article:
|A|0x01|<->|B|0x03|<->|C|0x03|
we will name the new field link = prev XOR next. therefore, with this in mind:
A.link = 0^0x01 = 0x01 B.link = 0x01^0x02 = 0x03 C.link = 0x03^0x0 = 0x03.
Assuming you have a pointer to a list header (which, as you know, has a prev pointer that is null) here, how do you iterate over a list:
p=head; prev = 0; while(p.link!=prev) { next = p.link^prev prev=p p=next }
You go back in the list using the same logic.
Pandrei
source share