Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order.

Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order.
class N:
    def __init__(s, v, nx=None): s.v, s.nx = v, nx
def odd_even(h):
    if not h: return h
    odd, even = h, h.nx; eh = even
    while even and even.nx:
        odd.nx = even.nx; odd = odd.nx
        even.nx = odd.nx; even = even.nx
    odd.nx = eh
    return h
h = None
for v in reversed([2, 1, 3, 5, 6, 4, 7]): h = N(v, h)
h = odd_even(h); out = []
while h: out.append(h.v); h = h.nx
print(*out)
What is printed?
  1. A. 1 3 5 7 2 6 4
  2. B. 2 3 6 7 1 4 5
  3. C. 1 5 7 2 3 6 4
  4. D. 2 3 6 7 1 5 4

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

Grouping is by position, not by value: positions 1, 3, 5, 7 hold 2, 3, 6, 7 and positions 2, 4, 6 hold 1, 5, 4. Grouping odd VALUES first would give '1 3 5 7 2 6 4', the trap.

More Coding Interview Problems questions

Exams that ask this topic