简繁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/zh-tw/leetcode-reorder-list/