2 Add Two Numbers
You are given two non-empty
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 may assume the two numbers do not contain any leading zero, except the number 0 itself.
1 | Example: |
Problem Analysis
We can not directly turn the input list to the Integer or lang data type since the input might be very long and it will exceed the limits of int or lang. So, we go through each node and record it carries for the next nodes.
Algorithm Analysis
Create a dummy node to record the result. Go through both input lists and sum the value up. If one of the lists meet the end, we assume it’s value is equal to 0. Use a carry variable to record if we need to add 1 to the next nodes and don’t forget to check the value of carrying after traversing two lists.
Time Complexity Analysis
Time: O(N) N is the length of the longer list
Space: O(1)
Code Implementation
1 | /** |