What it teaches: Grade-school addition on linked lists: walk both lists, carry the tens digit, and build the result behind a dummy head.
Practise it on judges as “Add Two Numbers”.
The problem
Two non-negative integers are stored as linked lists with digits in reverse order (ones digit first). Add them and return the sum as a list in the same format.
→ Digits in reverse order = addition from the ones place
→ Lists of different lengths and a final carry
These clues point to Dummy Head and Merging: Start with a fake node before the real head so building, merging and deleting never need special cases for the first node.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0), tail = dummy;
int carry = 0;
return dummy.next;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.