LeetCode 143. Reorder List

题目

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:

1
Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

1
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

思路

linked list的经典题。
split_list(mid-point finding), reverse_list, merge_list的融合体。

代码

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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head:
# Quick response for empty linked list
return None

# ------------------------------------------
# Locate the mid point of linked list
# First half is the linked list before mid point
# Second half is the linked list after mid point

fast, slow = head, head

while fast and fast.next:
slow, fast = slow.next, fast.next.next

mid = slow

# ------------------------------------------
# Reverse second half

prev, cur = None, mid

while cur:
cur.next, prev, cur = prev, cur, cur.next

head_of_second_rev = prev

# ------------------------------------------
# Update link between first half and reversed second half

first, second = head, head_of_second_rev

while second.next:

next_hop = first.next
first.next = second
first = next_hop

next_hop = second.next
second.next = first
second = next_hop