File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments