Data Structures & AlgorithmsHardGATE CS · DSA
Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?
Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?
def remove_nth(h, n):
d = N(0, h); fast = slow = d
for _ in range(n + 1): fast = fast.nx
while fast: fast, slow = fast.nx, slow.nx
slow.nx = slow.nx.nx
return d.nx
print(vals(remove_nth(build([59, 72, 52, 43, 88, 82, 14]), 2)))- A. [59, 72, 52, 43, 88, 14]
- B. [59, 72, 52, 43, 88, 82]
- C. [59, 72, 43, 52, 88, 14]
- D. [59, 72, 52, 43, 82, 14]
Correct answer: A. [59, 72, 52, 43, 88, 14]
fast starts n + 1 steps ahead of slow (both from the dummy), so when fast falls off the end, slow is just before the node to delete; the dummy also handles deleting the head. Output: [59, 72, 52, 43, 88, 14].
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
- Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than…
- Evaluate the postfix expression 7 4 − 2 + 6 − 8 × 7 1 + + (all divisions are exact). What is its value, and what is the maximum number of…
- KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed? python def lps(p)…
- A sorted array was rotated to give [58, 67, 70, 71, 77, 3, 12, 14, 55]. Binary search finds the index of the minimum: while lo < hi, mid =…
- A string s has length n. What is the time complexity of building s by repeated concatenation s = s + c in a language with immutable…
- What does this loop-counting code print? (Python) python n, c = 10, 0 for i in range(n): for j in range(i + 1, n): for k in range(j + 1…