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([51, 61, 86, 64, 81, 53, 26]), 4)))
  1. A. [51, 61, 64, 81, 53, 26]
  2. B. [51, 61, 86, 64, 53, 26]
  3. C. [51, 61, 86, 81, 53, 26]
  4. D. [51, 61, 81, 86, 53, 26]

Correct answer: C. [51, 61, 86, 81, 53, 26]

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: [51, 61, 86, 81, 53, 26].

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

Exams that ask this topic