简繁EN

LeetCodeNo. 099

【LeetCode with Python】 143. Reorder List

目录

题目

原题页面:https://leetcode.com/problems/reorder-list/
题目类型:Linked List
难度评价:Medium

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.


分析

我的做法是先数一遍节点个数count,count小于等于2时什么都不用动,直接返回;否则从中间断开,前半段是前ceil(count/2)个节点。代码里half_count = (count - 1) / 2,cur2从head往后走half_count步,停在前半段最后一个节点上,然后cur2.next = None,两段就断开了。

我只把后半段原地反转,前半段的顺序没动过,也就不用拷贝原链表了。

接着把反转后的后半段节点依次插到前半段的节点后面,一共插count / 2(整除)次。比如{1,2,3,4},后半段反转成4→3,和前半段1→2穿插起来就是1→4→2→3。全程只改next指针,时间复杂度是O(n),额外空间是O(1)。


代码

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
# Reverse the nodes from head up to (but not including) end, and link the
# old head, which becomes the last reversed node, to tail_next.
# @param head, a ListNode
# @param tail_next, a ListNode or None
# @param end, a ListNode or None
# @return the new head of the reversed part
def reverse_list(head, tail_next, end):
prev = tail_next
cur = head
while end != cur:
cur_next = cur.next
cur.next = prev
prev = cur
cur = cur_next
return prev

class Solution:

# @param head, a ListNode
# @return nothing
def reorderList(self, head):

if None == head:
return
cur = head
count = 0
while None != cur:
cur = cur.next
count += 1
if count <= 2:
return

half_count = (count - 1) / 2
cur2 = head
for i in range(0, half_count):
cur2= cur2.next
cur2_next = cur2.next
cur2.next = None
cur2 = reverse_list(cur2_next, None, None)

cur1 = head
time_count = int(count / 2)
for i in range(0, time_count):
cur2_next = cur2.next
cur2.next = cur1.next
cur1.next = cur2
cur1 = cur2.next
cur2 = cur2_next

本文地址:https://xnerv.wang/leetcode-reorder-list/