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([8, 57, 39, 2, 28, 5, 15, 42]))))
  1. A. [8, 39, 15, 28, 57, 2, 5, 42]
  2. B. [8, 39, 28, 15]
  3. C. [8, 39, 28, 15, 57, 5, 2, 42]
  4. D. [8, 39, 28, 15, 57, 2, 5, 42]

Correct answer: D. [8, 39, 28, 15, 57, 2, 5, 42]

The rearrangement is by position, not by value parity: positions 1, 3, 5, … then 2, 4, 6, …. Output: [8, 39, 28, 15, 57, 2, 5, 42].

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

Exams that ask this topic