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)))
  1. A. [4, 3, 2, 1, 8, 7, 6, 5, 9, 10]
  2. B. [4, 3, 2, 1]
  3. C. [4, 3, 2, 1, 5, 6, 7, 8, 9, 10]
  4. 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].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic