File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
data_structures/linked_list Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ XOR Linked List implementation
3+
4+ A memory-efficient doubly linked list using XOR of node addresses.
5+ Each node stores one pointer that is the XOR of previous and next node addresses.
6+
7+ Example:
8+ >>> xor_list = XORLinkedList()
9+ >>> xor_list.insert(10)
10+ >>> xor_list.insert(20)
11+ >>> xor_list.insert(30)
12+ >>> xor_list.to_list()
13+ [10, 20, 30]
14+ """
15+
16+ from typing import Optional
17+
18+
19+ class Node :
20+ def __init__ (self , value : int ):
21+ self .value = value
22+ self .both : int = 0 # XOR of prev and next node ids
23+
24+
25+ class XORLinkedList :
26+ def __init__ (self ):
27+ self .head : Optional [Node ] = None
28+ self .tail : Optional [Node ] = None
29+ self ._nodes = {} # id → node map to simulate pointer references
30+
31+ def _xor (self , a : Optional [Node ], b : Optional [Node ]) -> int :
32+ return (id (a ) if a else 0 ) ^ (id (b ) if b else 0 )
33+
34+ def insert (self , value : int ) -> None :
35+ node = Node (value )
36+ self ._nodes [id (node )] = node
37+ if self .head is None :
38+ self .head = self .tail = node
39+ else :
40+ node .both = id (self .tail )
41+ self .tail .both ^= id (node )
42+ self .tail = node
43+
44+ def to_list (self ) -> list [int ]:
45+ result = []
46+ prev_id = 0
47+ current = self .head
48+ while current :
49+ result .append (current .value )
50+ next_id = prev_id ^ current .both
51+ prev_id = id (current )
52+ current = self ._nodes .get (next_id )
53+ return result
54+
55+
56+ if __name__ == "__main__" :
57+ import doctest
58+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments