From ee33a389a23b9a18efc8b660fc3ef425e2ecf2fa Mon Sep 17 00:00:00 2001 From: pro100ton Date: Sun, 16 Feb 2025 19:21:39 +0300 Subject: [PATCH] Add solution for LL: reorder linked list --- .../linked_list/reorder_linked_list/README.md | 38 ++++++++++++++++ .../reorder_linked_list/solution.py | 43 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 neetcode/linked_list/reorder_linked_list/README.md create mode 100644 neetcode/linked_list/reorder_linked_list/solution.py diff --git a/neetcode/linked_list/reorder_linked_list/README.md b/neetcode/linked_list/reorder_linked_list/README.md new file mode 100644 index 0000000..fa153e1 --- /dev/null +++ b/neetcode/linked_list/reorder_linked_list/README.md @@ -0,0 +1,38 @@ +Reorder Linked List +You are given the head of a singly linked-list. + +The positions of a linked list of length = 7 for example, can intially be represented as: + +[0, 1, 2, 3, 4, 5, 6] + +Reorder the nodes of the linked list to be in the following order: + +[0, 6, 1, 5, 2, 4, 3] + +Notice that in the general case for a list of length = n the nodes are reordered to be in the following order: + +[0, n-1, 1, n-2, 2, n-3, ...] + +You may not modify the values in the list's nodes, but instead you must reorder the nodes themselves. + +Example 1: + +Input: head = [2,4,6,8] + +Output: [2,8,4,6] +Example 2: + +Input: head = [2,4,6,8,10] + +Output: [2,10,4,8,6] +Constraints: + +1 <= Length of the list <= 1000. +1 <= Node.val <= 1000 + +# Solution + +input = [0, 1, 2, 3, 4, 5, 6] +index = 0 + + diff --git a/neetcode/linked_list/reorder_linked_list/solution.py b/neetcode/linked_list/reorder_linked_list/solution.py new file mode 100644 index 0000000..75bb6fc --- /dev/null +++ b/neetcode/linked_list/reorder_linked_list/solution.py @@ -0,0 +1,43 @@ +from typing import List, Optional + + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + nodes: List[ListNode] = [] + sorted_nodes: List[ListNode] = [] + while head: + nodes.append(head) + head = head.next + right = len(nodes) - 1 + left = 0 + counter = 0 + while left <= right: + if counter % 2 == 0: + sorted_nodes.append(nodes[left]) + left += 1 + else: + sorted_nodes.append(nodes[right]) + right -= 1 + counter += 1 + for sni in range(0, len(sorted_nodes) - 1): + sorted_nodes[sni].next = sorted_nodes[sni + 1] + sorted_nodes[-1].next = None + return sorted_nodes[0] + + +if __name__ == "__main__": + s = Solution() + e3 = ListNode(8, None) + e2 = ListNode(6, e3) + e1 = ListNode(4, e2) + e0 = ListNode(2, e1) + fe = s.reorderList(e0) + while fe: + print(f"{fe.val}") + fe = fe.next