Data Structures & AlgorithmsModerateTCS Digital · Infosys SP

Delete every alternate node (2nd, 4th, …) of a linked list, then reverse what remains. What is printed?

Delete every alternate node (2nd, 4th, …) of a linked list, then reverse what remains. What is printed?
def del_alt(h):
    p = h
    while p and p.nx:
        p.nx = p.nx.nx
        p = p.nx
    return h
def rev(h):
    prev = None
    while h: h.nx, prev, h = prev, h, h.nx
    return prev
print(vals(rev(del_alt(build([59, 53, 47, 55, 38, 1, 35, 29, 17])))))
  1. A. [17, 38, 35, 47, 59]
  2. B. [59]
  3. C. [17, 35, 38, 47, 59]
  4. D. [17, 35, 38, 59, 47]

Correct answer: C. [17, 35, 38, 47, 59]

After each deletion p jumps to the node that followed the deleted one, so positions 1, 3, 5, … survive; reversing them gives [17, 35, 38, 47, 59].

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

Exams that ask this topic