Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft

Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative order. What is printed?

Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative order. What is printed?
def odd_even(h):
    if not h: return h
    odd, even = h, h.nx
    ehead = even
    while even and even.nx:
        odd.nx = even.nx; odd = odd.nx
        even.nx = odd.nx; even = even.nx
    odd.nx = ehead
    return h
print(vals(odd_even(build([54, 20, 7, 17, 27, 38, 22, 49]))))
  1. A. [54, 7, 27, 20, 22, 17, 38, 49]
  2. B. [54, 7, 27, 22, 20, 17, 38, 49]
  3. C. [54, 7, 22, 27, 20, 17, 38, 49]
  4. D. [54, 7, 27, 22]

Correct answer: B. [54, 7, 27, 22, 20, 17, 38, 49]

The rearrangement is by position, not by value parity: positions 1, 3, 5, … then 2, 4, 6, …. Output: [54, 7, 27, 22, 20, 17, 38, 49].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic