Linked Lists
62 / 170Linked ListsLesson 7 of 12About 37 min
Arithmetic on lists, and the loop condition that handles both lists ending at different times.
This version stops as soon as both lists are exhausted, ignoring a leftover carry. Type what it prints.
class Node: def __init__(self, val, next=None): self.val, self.next = val, next def build(values): head = None for value in reversed(values): head = Node(value, head) return head def to_list(node): out = [] while node: out.append(node.val) node = node.next return out def add_broken(a, b): dummy = Node(0) tail = dummy carry = 0 while a or b: total = carry if a: total += a.val a = a.next if b: total += b.val b = b.next carry, digit = divmod(total, 10) tail.next = Node(digit) tail = tail.next return dummy.next print(to_list(add_broken(build([9, 9]), build([1]))))Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.