Skip to content

Commit e0c55fc

Browse files
committed
LeetCode #143: Reorder List
1 parent 32d4ab4 commit e0c55fc

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from typing import Optional
2+
3+
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
10+
class Solution:
11+
12+
def print_linked_list(self, head):
13+
current = head
14+
while current is not None:
15+
print(current.val, end="")
16+
current = current.next
17+
print()
18+
19+
def reorderList(self, head: Optional[ListNode]) -> None:
20+
slow, fast = head, head
21+
22+
while fast and fast.next:
23+
slow = slow.next
24+
fast = fast.next.next
25+
half = slow.next
26+
slow.next = None
27+
28+
prev = None
29+
while half:
30+
next_node = half.next
31+
half.next = prev
32+
prev = half
33+
half = next_node
34+
35+
while head and prev:
36+
next_head = head.next
37+
head.next = prev
38+
next_prev = prev.next
39+
prev.next = next_head
40+
head = next_head
41+
prev = next_prev

0 commit comments

Comments
 (0)