Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP
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([7, 19, 24, 28]), build([8, 16, 17, 18, 22])
m = merge(x, y)
print(vals(m), vals(x))- A. [7, 8, 16, 17, 18, 19, 22, 24, 28] [7, 19, 24, 28]
- B. [7, 8, 16, 17, 18, 22, 19, 24, 28] [7, 8, 16, 17, 18, 19, 22, 24, 28]
- C. [7, 8, 16, 17, 18, 19, 22, 24, 28] [7, 8, 16, 17, 18, 19, 22, 24, 28]
- D. [7, 8, 16, 17, 18, 19, 22, 28, 24] [7, 8, 16, 17, 18, 19, 22, 24, 28]
Correct answer: C. [7, 8, 16, 17, 18, 19, 22, 24, 28] [7, 8, 16, 17, 18, 19, 22, 24, 28]
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: [7, 8, 16, 17, 18, 19, 22, 24, 28] [7, 8, 16, 17, 18, 19, 22, 24, 28].
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
- Print a matrix in spiral order (right, down, left, up, repeat). What is printed? python m = [[90, 11, 62, 33], [40, 71, 82, 13], [10, 81…
- A 2-D array A[0..11][0..29] of 4-byte elements is stored in row-major order starting at address 1000. What is the address of A[5][11]?
- For the sorted array [1, 5, 6, 7, 7, 7, 8, 9, 9, 10, 10, 11] (0-based), what are lowerbound(9) (first index with value ≥ 9) and…
- Keys 13, 14, 24, 27, 70, 76, 91, 15 are inserted in this order into an empty hash table of size 13 with h(k) = k mod 13 and linear…
- Keys 55, 63, 47, 69, 16, 97, 39, 99, 77, 43 are inserted in this order into a chained hash table with 7 buckets, h(k) = k mod 7, and each…
- Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle…