Data Structures & AlgorithmsHardGATE CS · DSA

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([36, 26, 4, 7, 22, 45, 41, 34]))))
  1. A. [26, 36, 7, 4, 45, 22, 34, 41]
  2. B. [26, 36, 7, 4, 45, 22, 41, 34]
  3. C. [36, 26, 7, 4, 45, 22, 34, 41]
  4. D. [26, 4, 7, 22, 45, 41, 34, 36]

Correct answer: A. [26, 36, 7, 4, 45, 22, 34, 41]

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: [26, 36, 7, 4, 45, 22, 34, 41].

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

Exams that ask this topic