Data Structures & AlgorithmsModerateTCS Digital · Infosys SP

Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What is printed?

Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What is printed?
def partition(h, x):
    ls = lt = N(0); gs = gt = N(0)
    while h:
        if h.v < x: lt.nx = h; lt = h
        else: gt.nx = h; gt = h
        h = h.nx
    gt.nx = None
    lt.nx = gs.nx
    return ls.nx
print(vals(partition(build([18, 1, 17, 10, 14, 16, 19, 11]), 11)))
  1. A. [18, 17, 14, 16, 19, 11, 10]
  2. B. [1, 10, 11, 18, 17, 14, 16, 19]
  3. C. [10, 1, 18, 17, 14, 16, 19, 11]
  4. D. [1, 10, 18, 17, 14, 16, 19, 11]

Correct answer: D. [1, 10, 18, 17, 14, 16, 19, 11]

Two dummy-headed chains collect < x and ≥ x nodes in scan order, then the first chain's tail points to the second chain. Setting gt.nx = None prevents a cycle. Output: [1, 10, 18, 17, 14, 16, 19, 11].

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

Exams that ask this topic