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)- A. [2, 5, 7]
- B. [5, 7, 2]
- C. [5, 2, 7]
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (finding the intersection node of two linked lists by switching heads) python class N: def init(s, v, n=None): s.v, s.n =…
- What is printed? (Java String vs StringBuilder) java String s = "ab"; s.concat("cd"); StringBuilder sb = new StringBuilder("ab")…
- What is printed? (counting sort on small values) python a = [4, 1, 3, 4, 2, 1, 0, 4] cnt = [0] 5 for x in a: cnt[x] += 1 for i in range(1…
- How many swaps does this bubble sort make, and how many passes run? python a = [5, 1, 4, 2, 8] swaps = passes = 0 for i in range(len(a)…
- Insertion sort counts element shifts. What is printed? python a = [3, 7, 1, 5, 2] shifts = 0 for i in range(1, len(a)): key, j = a[i], i…
- Quick sort with Lomuto partition (last element as pivot). What is the array after the FIRST partition, and the pivot's final index? python…