-
Notifications
You must be signed in to change notification settings - Fork 2
/
143. Reorder List.py
61 lines (51 loc) · 1.63 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Given a singly linked list L: L0→L1→…→Ln-1→Ln,
# reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
# You may not modify the values in the list's nodes, only nodes itself may be changed.
# Example 1:
# Given 1->2->3->4, reorder it to 1->4->2->3.
# Example 2:
# Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def findMiddle(self, head):
p2 = head
while p2 and p2.next:
head = head.next
p2 = p2.next.next
return head
def _reverse(self,head):
pre = None
while head:
curr, head = head, head.next
#head = head.next
curr.next, pre = pre, curr
#pre = curr
return pre
def _merge(self, head, headR):
while head.next and headR.next:
temp1 = head.next
temp2 = headR.next
head.next = headR
headR.next = temp1
head = temp1
headR = temp2
return
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
# 思路:分为3步:
# 求中点(可以先遍历找到中点,但更好的是快慢指针)
# 翻转后面的链表
# 两个链表合并
if not head or not head.next:
return
headR = self.findMiddle(head)
headR = self._reverse(headR)
self._merge(head, headR)
return