Data Structures & AlgorithmsVery hardGATE CS · DSA
Merge two sorted linked lists by relinking nodes (ties take the node from the first list). What is printed?
Merge two sorted linked lists by relinking nodes (ties take the node from the first list). What is printed?
def merge(a, b):
d = t = N(0)
while a and b:
if a.v <= b.v: t.nx, a = a, a.nx
else: t.nx, b = b, b.nx
t = t.nx
t.nx = a or b
return d.nx
x, y = build([9, 26, 28, 29]), build([6, 8, 14, 18, 29])
m = merge(x, y)
print(vals(m), vals(x))- A. [6, 8, 14, 9, 18, 26, 28, 29, 29] [9, 14, 18, 26, 28, 29, 29]
- B. [6, 8, 9, 14, 18, 26, 28, 29, 29] [9, 14, 18, 26, 28, 29, 29]
- C. [6, 8, 9, 18, 14, 26, 28, 29, 29] [9, 14, 18, 26, 28, 29, 29]
- D. [6, 8, 9, 14, 18, 26, 28, 29, 29] [9, 26, 28, 29]
Correct answer: B. [6, 8, 9, 14, 18, 26, 28, 29, 29] [9, 14, 18, 26, 28, 29, 29]
The merge relinks the original nodes, so x (still pointing at the first node of the first list) now walks along the merged chain from that node onwards. Output: [6, 8, 9, 14, 18, 26, 28, 29, 29] [9, 14, 18, 26, 28, 29, 29].
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
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 81 in [22, 26, 29, 31, 36, 38, 46, 51, 70, 81…
- The intervals [15, 16], [11, 16], [4, 9], [4, 8], [8, 12], [20, 22] are sorted by start and merged (intervals that touch, like [2, 4] and…
- For s = "cbbbccadbcdacd", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by…
- Keys 81, 25, 26, 79, 49, 55, 59, 93 are inserted in this order into an empty table of size 11 with h(k) = k mod 11 and linear probing…
- Only the lower triangle (including the diagonal) of a 10 × 10 matrix is stored COLUMN by column in a 1-D array B starting at B[0] (indices…
- A min-stack keeps a second stack of running minimums. What is printed? python st, mn, out = [], [], [] for op in [8, "pop", 8, 8, "pop"…