|
4 | 4 | from datastructures.linked_lists.singly_linked_list.node import SingleNode |
5 | 5 | from datastructures.linked_lists import LinkedList, T, Node |
6 | 6 | from datastructures.linked_lists.exceptions import EmptyLinkedList |
| 7 | +from datastructures.linked_lists.singly_linked_list.single_linked_list_utils import ( |
| 8 | + reverse_list, |
| 9 | + merge_and_weave, |
| 10 | +) |
7 | 11 |
|
8 | 12 |
|
9 | 13 | class SinglyLinkedList(LinkedList): |
@@ -983,6 +987,36 @@ def reverse_list(head_node: SingleNode) -> SingleNode: |
983 | 987 | def remove_tail(self): |
984 | 988 | pass |
985 | 989 |
|
| 990 | + def reorder_list(self) -> Optional[SingleNode]: |
| 991 | + """ |
| 992 | + Reorders the linked list in place. |
| 993 | + Returns: |
| 994 | + head node of reversed linked list |
| 995 | + """ |
| 996 | + # return early if there is no head node |
| 997 | + if self.head is None: |
| 998 | + return None |
| 999 | + |
| 1000 | + # first split the linked list into two halves. To do this without knowing the length of the linked list beforehand |
| 1001 | + # we must first find the middle node. This uses the slow & fast pointer approach |
| 1002 | + middle_node = self.middle_node() |
| 1003 | + |
| 1004 | + # Store the second half head node |
| 1005 | + second_half_head = middle_node.next |
| 1006 | + # cut the connection between the first half and the second half |
| 1007 | + middle_node.next = None |
| 1008 | + |
| 1009 | + # Now, we need to reverse the second half of the linked list in place |
| 1010 | + # The reversal step involves taking the second half of the linked list and reversing it in place |
| 1011 | + # for example, if the linked list is 1 -> 2 -> 3 -> 4 -> 5, the second half is 3 -> 4 -> 5 |
| 1012 | + # after reversing, it becomes 5 -> 4 -> 3 |
| 1013 | + reversed_second_half = self.reverse_list(second_half_head) |
| 1014 | + |
| 1015 | + # now we can merge and weave the first half and the reversed second half |
| 1016 | + reordered_list = merge_and_weave(self.head, reversed_second_half) |
| 1017 | + |
| 1018 | + return reordered_list |
| 1019 | + |
986 | 1020 | def kth_to_last_node(self, k: int) -> Optional[SingleNode]: |
987 | 1021 | """ |
988 | 1022 | Gets the Kth to the last node. |
|
0 commit comments