[LeetCode] Challenge log 143

143. Reorder List

Algorithm:

  1. split the linklist
  2. reverse the second half
  3. merge one by one

Given a singly linked list L: L0→L1→…→L**n-1→Ln,
reorder it to: L0→L**nL1→L**n-1→L2→L**n-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.

Soulution:
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
class Solution:
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head or not head.next:
pass
else:
# return node at len // 2
newHead = ListNode(0)
newHead.next = head
slow = newHead
fast = newHead
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
mid = slow

# reverse the second half as head2
tail = None
cur = mid.next
mid.next = None # important! aviod cycle!!!
while cur:
nxt = cur.next
cur.next = tail
tail = cur
cur = nxt
head2 = tail


# link one by one
p1 = head
p2 = head2
res = ListNode(0)
cur = res
while p1 or p2:
if p1:
cur.next = p1
cur = cur.next
p1 = p1.next
if p2:
cur.next = p2
cur = cur.next
p2 = p2.next
0%