Skip to content

Commit 71078c7

Browse files
committed
Time: 61 ms (99.71%), Space: 26.3 MB (15.45%) - LeetHub
1 parent 91254c9 commit 71078c7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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 middle(self, head):
8+
prev = ListNode(0, head)
9+
slow = head; fast = head
10+
while fast:
11+
prev, slow = slow, slow.next
12+
try:
13+
fast = fast.next.next
14+
except:
15+
break
16+
prev.next = None
17+
return slow
18+
19+
def rev(self, head):
20+
prev = None
21+
nd = head
22+
while nd:
23+
nxt = nd.next
24+
nd.next = prev
25+
prev, nd = nd, nxt
26+
return prev
27+
28+
def reorderList(self, head: Optional[ListNode]) -> None:
29+
"""
30+
Do not return anything, modify head in-place instead.
31+
"""
32+
mid = self.middle(head)
33+
revhead = self.rev(mid)
34+
dummy = ListNode(); tail = dummy
35+
36+
while head and revhead:
37+
tail.next = head
38+
tail = tail.next
39+
head = head.next
40+
41+
tail.next = revhead
42+
tail = tail.next
43+
revhead = revhead.next
44+
45+
if head:
46+
tail.next = head
47+

0 commit comments

Comments
 (0)