-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy path_linked_list.py
More file actions
284 lines (235 loc) · 10.3 KB
/
_linked_list.py
File metadata and controls
284 lines (235 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
"""Mutable list for nodes in a graph with safe mutation properties."""
from __future__ import annotations
from collections.abc import Iterable, Iterator, Sequence
from typing import Generic, TypeVar, overload
T = TypeVar("T")
class _LinkBox(Generic[T]):
"""A link in a doubly linked list that has a reference to the actual object in the link.
The :class:`_LinkBox` is a container for the actual object in the list. It is used to
maintain the links between the elements in the linked list. The actual object is stored in the
:attr:`value` attribute.
By using a separate container for the actual object, we can safely remove the object from the
list without losing the links. This allows us to remove the object from the list during
iteration and place the object into a different list without breaking any chains.
This is an internal class and should only be initialized by the :class:`DoublyLinkedSet`.
Attributes:
prev: The previous box in the list.
next: The next box in the list.
erased: A flag to indicate if the box has been removed from the list.
owning_list: The :class:`DoublyLinkedSet` to which the box belongs.
value: The actual object in the list.
"""
__slots__ = ("next", "owning_list", "prev", "value")
def __init__(self, owner: DoublyLinkedSet[T], value: T | None) -> None:
"""Create a new link box.
Args:
owner: The linked list to which this box belongs.
value: The value to be stored in the link box. When the value is None,
the link box is considered erased (default). The root box of the list
should be created with a None value.
"""
self.prev: _LinkBox[T] = self
self.next: _LinkBox[T] = self
self.value: T | None = value
self.owning_list: DoublyLinkedSet[T] = owner
@property
def erased(self) -> bool:
return self.value is None
def erase(self) -> None:
"""Remove the link from the list and detach the value from the box."""
if self.value is None:
raise ValueError("_LinkBox is already erased")
# Update the links
prev, next_ = self.prev, self.next
prev.next, next_.prev = next_, prev
# Detach the value
self.value = None
def __repr__(self) -> str:
return f"_LinkBox({self.value!r}, erased={self.erased}, prev={self.prev.value!r}, next={self.next.value!r})"
class DoublyLinkedSet(Sequence[T], Generic[T]):
"""A doubly linked ordered set of nodes.
The container can be viewed as a set as it does not allow duplicate values. The order of the
elements is maintained. One can typically treat it as a doubly linked list with list-like
methods implemented.
Adding and removing elements from the set during iteration is safe. Moving elements
from one set to another is also safe.
During the iteration:
- If new elements are inserted after the current node, the iterator will
iterate over them as well.
- If new elements are inserted before the current node, they will
not be iterated over in this iteration.
- If the current node is lifted and inserted in a different location,
iteration will start from the "next" node at the _original_ location.
Time complexity:
Inserting and removing nodes from the set is O(1). Accessing nodes by index is O(n),
although accessing nodes at either end of the set is O(1). I.e.
``linked_set[0]`` and ``linked_set[-1]`` are O(1).
Values need to be hashable. ``None`` is not a valid value in the set.
"""
__slots__ = ("_length", "_root", "_value_ids_to_boxes")
def __init__(self, values: Iterable[T] | None = None) -> None:
# Using the root node simplifies the mutation implementation a lot
# The list is circular. The root node is the only node that is not a part of the list values
root_ = _LinkBox(self, None)
self._root: _LinkBox = root_
self._length = 0
self._value_ids_to_boxes: dict[int, _LinkBox] = {}
if values is not None:
self.extend(values)
def __iter__(self) -> Iterator[T]:
"""Iterate over the elements in the list.
- If new elements are inserted after the current node, the iterator will
iterate over them as well.
- If new elements are inserted before the current node, they will
not be iterated over in this iteration.
- If the current node is lifted and inserted in a different location,
iteration will start from the "next" node at the _original_ location.
"""
box = self._root.next
while box is not self._root:
if box.owning_list is not self:
raise RuntimeError(f"Element {box!r} is not in the list")
if not box.erased:
assert box.value is not None
yield box.value
box = box.next
def __reversed__(self) -> Iterator[T]:
"""Iterate over the elements in the list in reverse order."""
box = self._root.prev
while box is not self._root:
if not box.erased:
assert box.value is not None
yield box.value
box = box.prev
def __len__(self) -> int:
assert self._length == len(self._value_ids_to_boxes), (
"Bug in the implementation: length mismatch"
)
return self._length
@overload
def __getitem__(self, index: int) -> T: ...
@overload
def __getitem__(self, index: slice) -> Sequence[T]: ...
def __getitem__(self, index):
"""Get the node at the given index.
Complexity is O(n).
"""
if isinstance(index, slice):
return tuple(self)[index]
if index >= self._length or index < -self._length:
raise IndexError(
f"Index out of range: {index} not in range [-{self._length}, {self._length})"
)
if index < 0:
# Look up from the end of the list
iterator = reversed(self)
item = next(iterator)
for _ in range(-index - 1):
item = next(iterator)
else:
iterator = iter(self) # type: ignore[assignment]
item = next(iterator)
for _ in range(index):
item = next(iterator)
return item
def _insert_one_after(
self,
box: _LinkBox[T],
new_value: T,
) -> _LinkBox[T]:
"""Insert a new value after the given box.
All insertion methods should call this method to ensure that the list is updated correctly.
Example::
Before: A <-> B <-> C
^v0 ^v1 ^v2
Call: _insert_one_after(B, v3)
After: A <-> B <-> new_box <-> C
^v0 ^v1 ^v3 ^v2
Args:
box: The box which the new value is to be inserted.
new_value: The new value to be inserted.
"""
if new_value is None:
raise TypeError(f"{self.__class__.__name__} does not support None values")
if box.value is new_value:
# Do nothing if the new value is the same as the old value
return box
if box.owning_list is not self:
raise ValueError(f"Value {box.value!r} is not in the list")
if (new_value_id := id(new_value)) in self._value_ids_to_boxes:
# If the value is already in the list, remove it first
self.remove(new_value)
# Create a new _LinkBox for the new value
new_box = _LinkBox(self, new_value)
# original_box <=> original_next
# becomes
# original_box <=> new_box <=> original_next
original_next = box.next
box.next = new_box
new_box.prev = box
new_box.next = original_next
original_next.prev = new_box
# Be sure to update the length and mapping
self._length += 1
self._value_ids_to_boxes[new_value_id] = new_box
return new_box
def _insert_many_after(
self,
box: _LinkBox[T],
new_values: Iterable[T],
):
"""Insert multiple new values after the given box."""
insertion_point = box
for new_value in new_values:
insertion_point = self._insert_one_after(insertion_point, new_value)
def remove(self, value: T) -> None:
"""Remove a node from the list."""
if (value_id := id(value)) not in self._value_ids_to_boxes:
raise ValueError(f"Value {value!r} is not in the list")
box = self._value_ids_to_boxes[value_id]
# Remove the link box and detach the value from the box
box.erase()
# Be sure to update the length and mapping
self._length -= 1
del self._value_ids_to_boxes[value_id]
def append(self, value: T) -> None:
"""Append a node to the list."""
_ = self._insert_one_after(self._root.prev, value)
def extend(
self,
values: Iterable[T],
) -> None:
for value in values:
self.append(value)
def insert_after(
self,
value: T,
new_values: Iterable[T],
) -> None:
"""Insert new nodes after the given node.
Args:
value: The value after which the new values are to be inserted.
new_values: The new values to be inserted.
"""
if (value_id := id(value)) not in self._value_ids_to_boxes:
raise ValueError(f"Value {value!r} is not in the list")
insertion_point = self._value_ids_to_boxes[value_id]
return self._insert_many_after(insertion_point, new_values)
def insert_before(
self,
value: T,
new_values: Iterable[T],
) -> None:
"""Insert new nodes before the given node.
Args:
value: The value before which the new values are to be inserted.
new_values: The new values to be inserted.
"""
if (value_id := id(value)) not in self._value_ids_to_boxes:
raise ValueError(f"Value {value!r} is not in the list")
insertion_point = self._value_ids_to_boxes[value_id].prev
return self._insert_many_after(insertion_point, new_values)
def __repr__(self) -> str:
return f"DoublyLinkedSet({list(self)})"