Skip to content

Commit a5b39a6

Browse files
committed
Add solution for 143. Reorder List
1 parent e41728d commit a5b39a6

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

reorder-list/bhyun-kim.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""
2+
143. Reorder List
3+
https://leetcode.com/problems/reorder-list/
4+
"""
5+
6+
from typing import Optional
7+
8+
class ListNode:
9+
def __init__(self, val=0, next=None):
10+
self.val = val
11+
self.next = next
12+
13+
"""
14+
Solution:
15+
To reorder the linked list, we can follow these steps:
16+
First, find the middle of the linked list using the slow and fast pointers.
17+
Reverse the second half of the linked list.
18+
Merge the first half and the reversed second half.
19+
20+
1. Find the middle of the linked list using the slow and fast pointers
21+
- Initialize the slow and fast pointers to the head of the linked list
22+
- Move the slow pointer by one step and the fast pointer by two steps
23+
until the fast pointer reaches the end of the linked list.
24+
2. Reverse the second half of the linked list
25+
- Initialize the prev and curr pointers to None and the middle node, respectively
26+
- Iterate through the second half of the linked list
27+
- Store the next node of the current node
28+
- Reverse the current node
29+
- Move the prev and curr pointers to the next nodes
30+
3. Merge the first half and the reversed second half
31+
- Initialize the first and second pointers to the head and the reversed second half, respectively
32+
- Iterate through the linked list
33+
- Store the next nodes of the first and second pointers
34+
- Update the next pointers of the first and second pointers
35+
- Move the first and second pointers to the next nodes
36+
37+
Time complexity: O(N)
38+
- We iterate through the linked list to find the middle node and reverse the second half
39+
- The time complexity is O(N)
40+
41+
Space complexity: O(1)
42+
- We only use constant extra space for the pointers
43+
- The space complexity is O(1)
44+
45+
"""
46+
47+
48+
class Solution:
49+
def reorderList(self, head: Optional[ListNode]) -> None:
50+
"""
51+
Do not return anything, modify head in-place instead.
52+
"""
53+
if not head or not head.next:
54+
return
55+
56+
slow, fast = head, head
57+
while fast and fast.next:
58+
slow = slow.next
59+
fast = fast.next.next
60+
61+
prev, curr = None, slow
62+
while curr:
63+
next_temp = curr.next
64+
curr.next = prev
65+
prev = curr
66+
curr = next_temp
67+
68+
first, second = head, prev
69+
while second.next:
70+
tmp1, tmp2 = first.next, second.next
71+
first.next = second
72+
second.next = tmp1
73+
first, second = tmp1, tmp2

0 commit comments

Comments
 (0)