Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (singly linked list, delete every node whose value equals x)

What is printed? (singly linked list, delete every node whose value equals x)
class N:
    def __init__(s, v, n=None): s.v, s.n = v, n
h = N(2, N(2, N(5, N(2, N(7, N(2))))))
def remove_all(h, x):
    d = N(0, h); p = d
    while p.n:
        if p.n.v == x: p.n = p.n.n
        else: p = p.n
    return d.n
r = remove_all(h, 2); out = []
while r: out.append(r.v); r = r.n
print(out)
  1. A. [2, 5, 7]
  2. B. [5, 7, 2]
  3. C. [5, 2, 7]
  4. D. [5, 7]

Correct answer: D. [5, 7]

A dummy head handles deleting the first nodes uniformly. When the next node matches, p stays put so consecutive matches are all removed; it advances only past a kept node. Without the dummy the leading 2s need special-case code. O(n), O(1) extra space.

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

Exams that ask this topic