Data Structures & AlgorithmsHardTCS Digital · Infosys SP

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([8, 2, 20, 12, 4, 14, 27, 45]))))
  1. A. [2, 8, 12, 20, 14, 4, 27, 45]
  2. B. [2, 8, 12, 20, 4, 14, 45, 27]
  3. C. [2, 8, 12, 20, 14, 4, 45, 27]
  4. D. [2, 20, 12, 4, 14, 27, 45, 8]

Correct answer: C. [2, 8, 12, 20, 14, 4, 45, 27]

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: [2, 8, 12, 20, 14, 4, 45, 27].

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

Exams that ask this topic