Sub topic 13
Going further: the XOR linked list
This chapter assumes you know the doubly linked node from earlier chapters, with its prev and next references. It also assumes you are comfortable with Python classes, generators, and the bitwise XOR operator ^. The XOR linked list is an optional extension. It shows how far you can push memory savings, and why most programs don't.
The idea: one link field instead of two
A doubly linked node stores two references. An XOR linked list stores one value per node: the XOR of the previous and next addresses.
link = address(prev) XOR address(next)XOR has a property that makes this work. If c = a ^ b, then c ^ a == b and c ^ b == a. So if you know the address of the node you came from, you can recover the address of the node ahead:
next = link XOR address(prev)You can walk in either direction using the same rule. The missing end is represented by address 0, so the head stores 0 ^ next and the tail stores prev ^ 0.
Why it needs a trick in Python
Python gives you no access to raw addresses, and the garbage collector can move or free objects it can't see references to. An XOR of two references hides both from the collector. So the version below simulates memory. Nodes live in two parallel lists, and an integer index plays the role of an address. Index 0 is reserved to mean "no node".
class XorList:
"""XOR linked list. Slot 0 is reserved and means 'no node'."""
def __init__(self):
self._values = [None]
self._links = [0]
self.head = 0
self.tail = 0
def push_back(self, value):
idx = len(self._values)
self._values.append(value)
self._links.append(self.tail) # tail ^ 0
if self.tail == 0:
self.head = idx
else:
self._links[self.tail] ^= idx # (prev ^ 0) becomes (prev ^ idx)
self.tail = idx
def _walk(self, start):
prev, cur = 0, start
while cur != 0:
yield self._values[cur]
prev, cur = cur, self._links[cur] ^ prev
def __iter__(self):
return self._walk(self.head)
def reversed(self):
return self._walk(self.tail)
lst = XorList()
for v in (1, 2, 3):
lst.push_back(v)
print(list(lst)) # [1, 2, 3]
print(list(lst.reversed())) # [3, 2, 1]Look at the update in push_back. The old tail held prev ^ 0. XORing it with the new index turns it into prev ^ new, which is what a middle node should hold. The _walk generator is one function for both directions. Only the starting node changes.
Costs compared with a doubly linked list
| Property | Doubly linked | XOR linked |
|---|---|---|
| Link fields per node | 2 | 1 |
| Push and pop at either end | O(1) | O(1) |
| Traverse in either direction | Yes | Yes |
| Remove a node given only that node | O(1) | Not possible without a neighbor |
| Works with a garbage collector | Yes | No, in the pointer form |
| Easy to debug | Yes | No |
The saving is one pointer per node, typically 8 bytes. The price is that a node no longer describes its own neighbors. You must carry the previous node along as you walk. That breaks the O(1) removal by node reference that made doubly linked lists useful for LRU caches.
Common errors
- Starting a walk with the wrong
prev. Starting at the head needsprev = 0. Starting anywhere else with a guessedprevsends you to a wrong node, and nothing detects it. - Forgetting to patch the old tail. If you skip the
^= idxstep inpush_back, forward traversal stops after the old tail. - Reusing freed slots carelessly. In the simulated version, deleted slots stay in the lists. A real implementation needs a free list, and a stale index silently corrupts traversal.
Exercise
You are standing at node B and you arrived from node A. B stores link = A ^ C. How do you find C, and what do you do if you arrived from C instead?
Show answer
Compute link ^ A, which gives (A ^ C) ^ A = C. If you arrived from C, compute link ^ C, which gives A. The same rule works in both directions: XOR the stored link with the node you just left.