Skip to content

Commit 1e2c88e

Browse files
committed
Fix mypy typing in doubly_to_singly
1 parent 68473af commit 1e2c88e

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

data_structures/linked_list/doubly_linked_list.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from data_structures.linked_list import singly_linked_list
2+
13
"""
24
https://en.wikipedia.org/wiki/Doubly_linked_list
35
"""
@@ -187,6 +189,47 @@ def is_empty(self):
187189
"""
188190
return len(self) == 0
189191

192+
def doubly_to_singly(self) -> singly_linked_list.Node | None:
193+
"""
194+
Convert this doubly linked list into a singly linked list.
195+
196+
A new singly linked list is created by copying the data from
197+
each node in the doubly linked list.
198+
199+
Returns
200+
-------
201+
singly_linked_list.Node | None
202+
The head node of the newly created singly linked list.
203+
204+
Example
205+
-------
206+
>>> dll = DoublyLinkedList()
207+
>>> dll.insert_at_tail(1)
208+
>>> dll.insert_at_tail(2)
209+
>>> dll.insert_at_tail(3)
210+
>>> head = dll.doubly_to_singly()
211+
>>> head.data
212+
1
213+
>>> head.next.data
214+
2
215+
>>> head.next.next.data
216+
3
217+
"""
218+
219+
if self.head is None:
220+
return None
221+
222+
doubly_current: Node | None = self.head.next
223+
new_head = singly_linked_list.Node(self.head.data)
224+
singly_current = new_head
225+
226+
while doubly_current:
227+
singly_current.next_node = singly_linked_list.Node(doubly_current.data)
228+
singly_current = singly_current.next_node
229+
doubly_current = doubly_current.next
230+
231+
return new_head
232+
190233

191234
def test_doubly_linked_list() -> None:
192235
"""
@@ -223,6 +266,25 @@ def test_doubly_linked_list() -> None:
223266
assert len(linked_list) == 9
224267
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))
225268

269+
# Test doubly_to_singly conversion
270+
dll = DoublyLinkedList()
271+
dll.insert_at_tail(1)
272+
dll.insert_at_tail(2)
273+
dll.insert_at_tail(3)
274+
275+
head = dll.doubly_to_singly()
276+
277+
assert head is not None
278+
s_head = head # type: singly_linked_list.Node
279+
280+
assert s_head.data == 1
281+
282+
assert s_head.next_node is not None
283+
assert s_head.next_node.data == 2
284+
285+
assert s_head.next_node.next_node is not None
286+
assert s_head.next_node.next_node.data == 3
287+
226288

227289
if __name__ == "__main__":
228290
from doctest import testmod

0 commit comments

Comments
 (0)