Data Structures & AlgorithmsHardGATE CS · DSA
Reverse a singly linked list in groups of k (a final group shorter than k is left as it is). What is printed?
Reverse a singly linked list in groups of k (a final group shorter than k is left as it is). What is printed?
def rev_k(h, k):
cnt, p = 0, h
while p and cnt < k: p = p.nx; cnt += 1
if cnt < k: return h
prev, cur = rev_k(p, k), h
for _ in range(k):
cur.nx, prev, cur = prev, cur, cur.nx
return prev
print(vals(rev_k(build([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 4)))- A. [4, 3, 2, 1, 8, 7, 6, 5, 9, 10]
- B. [4, 3, 2, 1]
- C. [4, 3, 2, 1, 5, 6, 7, 8, 9, 10]
- D. [4, 3, 2, 1, 8, 7, 6, 9, 5, 10]
Correct answer: A. [4, 3, 2, 1, 8, 7, 6, 5, 9, 10]
Each full block of k nodes is reversed and linked to the already-processed remainder; the short tail block keeps its order. Output: [4, 3, 2, 1, 8, 7, 6, 5, 9, 10].
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 = [[50, 81, 32, 23], [30, 61, 32, 23], [60, 51…
- A chained hash table stores n = 2,000 keys in m = 500 buckets with simple uniform hashing. What is the expected number of key comparisons…
- Bars of width 1 have heights [5, 5, 7, 8, 6, 5, 2, 8]. What is the area of the largest rectangle that fits under the histogram (computed…
- Product of all elements except self, using prefix and suffix products (no division). What is printed? python a = [2, 3, 3, 2, -1] n =…
- What does this loop-counting code print? (Python) python n, c = 16, 0 i = 1 while i < n: j = i while j < n: c += 1 j = 2 i += 1 print(c)
- For the sorted array [1, 3, 4, 6, 6, 9, 9, 11, 13, 14, 14, 15] (0-based), what are lowerbound(14) (first index with value ≥ 14) and…