|
| 1 | +from data_structures.linked_list import singly_linked_list |
| 2 | + |
1 | 3 | """ |
2 | 4 | https://en.wikipedia.org/wiki/Doubly_linked_list |
3 | 5 | """ |
@@ -187,6 +189,47 @@ def is_empty(self): |
187 | 189 | """ |
188 | 190 | return len(self) == 0 |
189 | 191 |
|
| 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 | + |
190 | 233 |
|
191 | 234 | def test_doubly_linked_list() -> None: |
192 | 235 | """ |
@@ -223,6 +266,25 @@ def test_doubly_linked_list() -> None: |
223 | 266 | assert len(linked_list) == 9 |
224 | 267 | assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) |
225 | 268 |
|
| 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 | + |
226 | 288 |
|
227 | 289 | if __name__ == "__main__": |
228 | 290 | from doctest import testmod |
|
0 commit comments