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([12, 13, 22, 28]), build([8, 9, 21, 22, 27])
m = merge(x, y)
print(vals(m), vals(x))- A. [8, 9, 13, 12, 21, 22, 22, 27, 28] [12, 13, 21, 22, 22, 27, 28]
- B. [8, 9, 12, 13, 21, 22, 22, 27, 28] [12, 13, 22, 21, 22, 27, 28]
- C. [8, 9, 12, 13, 21, 22, 22, 27, 28] [12, 13, 22, 28]
- D. [8, 9, 12, 13, 21, 22, 22, 27, 28] [12, 13, 21, 22, 22, 27, 28]
Correct answer: D. [8, 9, 12, 13, 21, 22, 22, 27, 28] [12, 13, 21, 22, 22, 27, 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: [8, 9, 12, 13, 21, 22, 22, 27, 28] [12, 13, 21, 22, 22, 27, 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
- ^ is exponentiation (highest precedence, right-associative); and / come next; + and − are lowest; others are left-associative. What is the…
- Keys 93, 31, 142, 74, 55, 139, 99 are inserted in this order into an empty table of size 11 by double hashing: h1(k) = k mod 11, h2(k) = 5…
- Using a sliding window with a last-seen index map, what is the length of the longest substring of "dbcedadaadcced" with all characters…
- Shell sort with gap sequence 4, 2, 1 (gapped insertion sort for each gap). What is the array after the gap-4 pass only? python a = [20…
- A 2-D array A[0..9][0..19] of 4-byte elements is stored in row-major order starting at address 1000. What is the address of A[7][7]?
- For each day, a monotonic stack finds how many days you must wait for a strictly warmer temperature (0 if never). What is printed? python…