Add solution for LL: reorder linked list
This commit is contained in:
parent
b8d841ffac
commit
ee33a389a2
2 changed files with 81 additions and 0 deletions
38
neetcode/linked_list/reorder_linked_list/README.md
Normal file
38
neetcode/linked_list/reorder_linked_list/README.md
Normal file
|
@ -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
|
||||||
|
|
||||||
|
|
43
neetcode/linked_list/reorder_linked_list/solution.py
Normal file
43
neetcode/linked_list/reorder_linked_list/solution.py
Normal file
|
@ -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
|
Loading…
Reference in a new issue