-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143_ReorderList.py
More file actions
55 lines (50 loc) · 1.45 KB
/
143_ReorderList.py
File metadata and controls
55 lines (50 loc) · 1.45 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
def splitlist(node):
fast = node
slow = node
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
head2 = slow.next
slow.next = None
return node, head2
def reverselist(node):
last = None
while node:
tmp = node.next
node.next = last
last = node
node = tmp
return last
def reverselist1(a, last=None):
if not a:
return last
tmp = a.next
a.next = last
return reverselist(tmp, a)
def mergelist(a, b):
tail = a
head = b
a = a.next
while b:
tail.next = b
tail = tail.next
b = b.next
if a:
a,b = b,a
return head
if not head or not head.next:
return
a, b = splitlist(head)
b = reverselist(b)
head = mergelist(a, b)