Two non-negative whole numbers are stored as linked lists, one digit per node, with the ones digit first. So the number 185 is the list 5 → 8 → 1. Add the two numbers and return their sum as a linked list in the same form.
185 + 37 = 222. Read off the lists, that is 5 + 7 = 12 (write 2, carry 1), then 8 + 3 + 1 = 12 (write 2, carry 1), then 1 + 1 = 2.
5 + 5 = 10: the carry from the last digit becomes a new node.
Adding 0 changes nothing: the answer is 24, which is 4 → 2.
Constraints
1 and 100 nodes.0 <= Node.val <= 90, unless the list is just [0].Ones digit first is exactly the order you add on paper, so walk both lists together from the front.
Write 185 + 37 on paper and you start at the right: 5 + 7, then 8 + 3 and the carry, then 1 and the carry. You work from the ones digit towards the bigger places, and each column hands at most a 1 to the next.
Time O(max(m, n))Space O(1)
The full walkthrough and code are part of Premium