简繁EN

LeetCodeNo. 099

[LeetCode with Python] 143. Reorder List

Contents

Problem

Problem page: https://leetcode.com/problems/reorder-list/
Topics: Linked List
Difficulty: 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}.


Analysis

I start by counting the nodes and return without changing anything if count is 2 or less; otherwise I split the list in the middle, leaving the first ceil(count/2) nodes in the first half. In the code, half_count = (count - 1) / 2. I move cur2 forward half_count steps from head, which puts it on the last node of the first half. Then cur2.next = None separates the two halves.

I reverse the second half in place, leaving the first half in its original order, so I don't need to copy the list.

As I walk the first half, I insert the next node from the reversed second half after the current node. That's count / 2 insertions (integer division). For example, with {1,2,3,4}, I reverse the second half to get 4→3 and interleave it with the first half 1→2 to get 1→4→2→3. I only change next pointers along the way, and the whole operation takes O(n) time and O(1) extra space.


Code

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

Article link: https://xnerv.wang/en/leetcode-reorder-list/