Add two numbers as a linked list
Question
You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You can also check on LeetCode 2. Add Two Numbers
Example:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
Solution
Thinking about the add operation in math and we know we need to calculate the number from backward and add 1 if exists sum of two digits are greater that 10. And repeat the process until we finished all nodes. But we have to care about the situation (9, 9, 9) + (1) -> (0, 0, 0, 1)
and at the end, we have to add one more node.
Code
1 | // Time: O(max(m, n)) |