Wednesday, June 28, 2006

Xor linked list

How to Maintain a double linked list using a single linked list?

Xor linked lists are a curious use of the bitwise exclusive disjunction (XOR) operation to decrease storage requirements for doubly-linked lists. An ordinary doubly-linked list stores addresses of the previous and next list items in each list node, requiring two address fields:

... A-1 A B C C+1 ...
<– prev <– prev <– prev <–
–> next –> next –> next –>
An Xor linked list compresses the same information into one address field by storing the bitwise XOR of the address for previous and the address for next in one field:

... A-1 A B C C+1 ...
–> A-1 XOR B <–> A XOR C <–> B XOR C+1 <–
When you traverse the list from left to right: supposing you are at B, you can take the address of the previous item, A, and XOR it with the value in the XOR field. You will then have the address for C and you can continue traversing the list. The same pattern applies in the other direction.

To start traversing the list in either direction from some point, you need the address of two consecutive items, not just one. If the addresses of the two consecutive items are reversed, you will end up traversing the list in the opposite direction.

This particular trick is generally discouraged for several reasons:

general-purpose debugging tools cannot follow the XOR chain, making debugging more difficult;
the price for the decrease in memory usage is an increase in code complexity, making maintenance more expensive; and
conservative garbage collection schemes do not work with data structures that do not contain literal pointers.
Also, modern computer systems usually have cheap and plentiful memory, so storage overhead is not normally an issue outside specialised embedded systems. Where it is still desirable to reduce the overhead of a linked list, unrolling provides a more practical approach (as well as other advantages, such as increasing cache performance and speeding random accesses).

1 comment:

Anonymous said...

Good fill someone in on and this post helped me alot in my college assignement. Say thank you you seeking your information.