-
Notifications
You must be signed in to change notification settings - Fork 0
/
143. Reorder List.py
39 lines (36 loc) · 1.06 KB
/
143. Reorder List.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
# Function for reversing
def reverse(self, head):
prev = None
current = head
while current:
prev, prev.next, current = current, prev, current.next
return prev
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if head is None:
return
fast = head.next
slow = head
# Catch the Middle of List (slow)
while fast and fast.next:
fast = fast.next.next
slow = slow.next
# Cut Middle of list then Reverse it
rev = self.reverse(slow.next)
slow.next = None
while rev:
h_next = head.next
r_next = rev.next
head.next = rev
rev.next = h_next
rev = r_next
head = h_next