Skip to content

Commit 0f53426

Browse files
committed
143. Reorder List Solution
1 parent 10410e5 commit 0f53426

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

reorder-list/doh6077.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def reorderList(self, head: Optional[ListNode]) -> None:
8+
"""
9+
Do not return anything, modify head in-place instead.
10+
"""
11+
# Time Complexity: O(N)
12+
# The order:
13+
# 0, n, 1, n -1, 2, n-3 ...
14+
# first Idea
15+
# need to save the index of the original head
16+
# Hashmap: iterate through the head until head it none, save index as key and head.val as value
17+
head_hash = {}
18+
temp = head
19+
index = 0
20+
length = 0
21+
# Save index and value in the hashmap
22+
while temp is not None:
23+
head_hash[index] = temp.val
24+
temp = temp.next
25+
index += 1
26+
length += 1
27+
# reset index to 0, and use it to iterate through the head again
28+
index = 0
29+
# to keep track of n-1, n-2, n-3 ...
30+
count = 1
31+
# Iterate through the head again and change the value based on the index
32+
while head is not None:
33+
res = index % 2
34+
# if the index is even number
35+
if res == 0:
36+
head.val = head_hash[index/2]
37+
# n, n-1, n-2 when the index is odd
38+
else:
39+
head.val = head_hash[length - count]
40+
count += 1
41+
index += 1
42+
head = head.next
43+

0 commit comments

Comments
 (0)