Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed?

Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed?
def swap_pairs(h):
    d = p = N(0, h)
    while p.nx and p.nx.nx:
        a, b = p.nx, p.nx.nx
        p.nx, a.nx, b.nx = b, b.nx, a
        p = a
    return d.nx
print(vals(swap_pairs(build([26, 1, 44, 35, 21, 41, 16, 15]))))
  1. A. [1, 44, 35, 21, 41, 16, 15, 26]
  2. B. [1, 26, 35, 41, 44, 21, 15, 16]
  3. C. [1, 26, 35, 44, 41, 21, 16, 15]
  4. D. [1, 26, 35, 44, 41, 21, 15, 16]

Correct answer: D. [1, 26, 35, 44, 41, 21, 15, 16]

Each step relinks p → b → a → (rest) and moves p to a, the node now second in the pair; an odd last node stays in place. Output: [1, 26, 35, 44, 41, 21, 15, 16].

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

Exams that ask this topic