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]))))- A. [1, 4, 9, 0, 1]
- B. [4, 1, 9, 0, 1]
- C. [4, 9, 1, 0, 1]
- 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].
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
- A monotonic deque reports the maximum of every window of size 3 in [14, 5, −3, 14, 5, 14, −5, 16, 4]. What is the SUM of all reported…
- Delete duplicates from a SORTED linked list. Version A keeps one copy of each value; version B removes every value that appears more than…
- Which data structure gives O(1) worst-case time for inserting and deleting at BOTH ends and also O(1) access by index?
- What is the length of the shortest contiguous subarray of [1, 3, 5, 6, 3, 3, 7, 9, 4, 9] whose sum is at least 20? (All values are…
- Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed? python from collections import defaultdict a = [1…
- Bubble sort (ascending; each pass compares adjacent pairs left to right and swaps if out of order) is applied to [5, 42, 29, 4, 41, 8, 53…