Skip to content

Commit 3418129

Browse files
committed
Merge branch 'master' of https://github.com/IneshAg/Python
2 parents 08fd580 + 02407fc commit 3418129

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

data_structures/linked_list/xor_linked_list.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@
1111
[10, 20, 30]
1212
"""
1313

14-
# Note: 'from typing import Optional' is no longer needed
15-
# as we use the modern 'Node | None' syntax.
14+
# Note: 'from typing import Optional' is removed as we use the modern '|' syntax.
1615

1716

1817
class Node:
@@ -25,19 +24,26 @@ def __init__(self, value: int) -> None:
2524
class XORLinkedList:
2625
def __init__(self) -> None:
2726
"""Initializes an empty XOR Linked List."""
27+
# Use 'Node | None' instead of 'Optional[Node]' (per ruff UP045)
2828
self.head: Node | None = None
2929
self.tail: Node | None = None
3030
# id -> node map to simulate pointer references
3131
self._nodes: dict[int, Node] = {}
3232

33-
def _xor(self, a: Node | None, b: Node | None) -> int:
34-
"""Helper function to get the XOR of two node IDs."""
35-
return (id(a) if a else 0) ^ (id(b) if b else 0)
33+
def _xor(self, node_a: Node | None, node_b: Node | None) -> int:
34+
"""
35+
Helper function to get the XOR of two node IDs (simulated addresses).
36+
Names 'node_a' and 'node_b' are used for descriptive parameters.
37+
"""
38+
id_a = id(node_a) if node_a else 0
39+
id_b = id(node_b) if node_b else 0
40+
return id_a ^ id_b
3641

3742
def insert(self, value: int) -> None:
3843
"""Inserts a value at the end of the list."""
3944
node = Node(value)
4045
self._nodes[id(node)] = node
46+
node_id = id(node)
4147

4248
if self.head is None:
4349
# If the list is empty, head and tail are the new node
@@ -51,7 +57,7 @@ def insert(self, value: int) -> None:
5157
# its previous node ID with the new node's ID.
5258
# self.tail.both was (prev_id ^ 0)
5359
# self.tail.both becomes (prev_id ^ new_node_id)
54-
self.tail.both ^= id(node)
60+
self.tail.both ^= node_id
5561
self.tail = node
5662

5763
def to_list(self) -> list[int]:
@@ -64,10 +70,11 @@ def to_list(self) -> list[int]:
6470
# Find next node's ID:
6571
# current.both = prev_id ^ next_id
6672
# so, next_id = prev_id ^ current.both
73+
current_id = id(current)
6774
next_id = prev_id ^ current.both
6875

6976
# Move forward
70-
prev_id = id(current)
77+
prev_id = current_id
7178
current = self._nodes.get(next_id)
7279
return result
7380

0 commit comments

Comments
 (0)