Data Structures & AlgorithmsModerateProduct placement · Amazon/Microsoft

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([36, 47, 37, 15, 40, 26, 24])))))
  1. A. [40, 24, 37, 36]
  2. B. [24, 37, 40, 36]
  3. C. [24, 40, 37, 36]
  4. D. [36]

Correct answer: C. [24, 40, 37, 36]

After each deletion p jumps to the node that followed the deleted one, so positions 1, 3, 5, … survive; reversing them gives [24, 40, 37, 36].

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

Exams that ask this topic