Data Structures & AlgorithmsModerateGATE CS · DSA

Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print?

Two numbers are stored as linked lists with digits in REVERSE order (units first). What does this addition print?
def add(a, b):
    d = t = N(0); c = 0
    while a or b or c:
        s = c + (a.v if a else 0) + (b.v if b else 0)
        c, t.nx = s // 10, N(s % 10)
        t = t.nx
        a = a.nx if a else None; b = b.nx if b else None
    return d.nx
print(vals(add(build([8, 6, 9, 9]), build([6, 4, 9]))))
  1. A. [1, 4, 9, 0, 1]
  2. B. [4, 1, 9, 0, 1]
  3. C. [4, 9, 1, 0, 1]
  4. D. [4, 1, 9, 0]

Correct answer: B. [4, 1, 9, 0, 1]

Digits are added units-first with a carry; the loop also runs while a carry remains, which can add an extra most-significant digit at the end. Output: [4, 1, 9, 0, 1].

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

Exams that ask this topic