Data Structures & Algorithms Linked Lists
💡
Exercise 66

Add Two Numbers 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Two non-empty linked lists represent non-negative integers stored in reverse order (least significant digit first). Add the two numbers and return the sum as a linked list.

# 2 → 4 → 3 represents 342 # 5 → 6 → 4 represents 465 # Sum: 342 + 465 = 807 # Output: 7 → 0 → 8

Simulate digit-by-digit addition with a carry. Process both lists simultaneously:

  • Add corresponding digits + carry
  • New digit = sum % 10
  • New carry = sum // 10
  • Continue until both lists are exhausted AND carry is 0
📋 Instructions
Implement `add_two_numbers(l1, l2)` that adds two numbers represented as linked lists. Add [2,4,3] (342) and [5,6,4] (465) and print the result digits.
Use a dummy node. While either list has nodes or carry > 0: sum = val1 + val2 + carry. Create new node with sum % 10. Update carry = sum // 10.
🧪 Test Cases
Input
Run your code
Expected
7 0 8
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.