Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge).

Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge).
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def reorder(h):
    slow = fast = h
    while fast.nx and fast.nx.nx: slow = slow.nx; fast = fast.nx.nx
    prev, cur = None, slow.nx; slow.nx = None
    while cur: cur.nx, prev, cur = prev, cur, cur.nx
    a, b = h, prev
    while b: a.nx, b.nx, a, b = b, a.nx, a.nx, b.nx
    return h
h = None
for v in [7, 6, 5, 4, 3, 2, 1]: h = N(v, h)
h = reorder(h); out = []
while h: out.append(h.v); h = h.nx
print(out)
What is printed?
  1. A. [1, 7, 2, 6, 3, 5]
  2. B. [1, 2, 3, 4, 7, 6, 5]
  3. C. [7, 1, 6, 2, 5, 3, 4]
  4. D. [1, 7, 2, 6, 3, 5, 4]

Correct answer: D. [1, 7, 2, 6, 3, 5, 4]

The middle of 1..7 is 4, so the first half is 1-2-3-4 and the reversed second half is 7-6-5. Interleaving gives 1, 7, 2, 6, 3, 5, 4; with an odd length the middle node ends the list.

More Coding Interview Problems questions

Exams that ask this topic