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)))- A. [51, 61, 64, 81, 53, 26]
- B. [51, 61, 86, 64, 53, 26]
- C. [51, 61, 86, 81, 53, 26]
- 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].
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
- In a singly linked list with only a head pointer, which operation CANNOT be done in O(1) time?
- Run-length encoding: each maximal run is written as the character followed by its length. What is printed? python s = "yyyyyyyyxx" out, i…
- In the binary array [0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1] you may flip at most 2 zeros to ones. What is the length of the longest run…
- Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than…
- Trains occupy a platform from arrival to departure INCLUSIVE, so a train arriving at the same minute another departs needs a separate…
- Counting sort on [1, 1, 2, 1, 0, 3, 3, 0, 2, 0] (values 0–4) builds count[], turns it into cumulative counts, then scans the input from…