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)))
  1. A. [59, 72, 52, 43, 88, 14]
  2. B. [59, 72, 52, 43, 88, 82]
  3. C. [59, 72, 43, 52, 88, 14]
  4. 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].

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

Exams that ask this topic