Add Two Numbers
Add the two numbers and return it as a linked list.
Question
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
Analyzation
- Since the numbers are added from the first to the last, which makes the problem simpler. We only need to create a new LinkedList
head(dummy)
that points to null and a tail that points to the first node of the first added number which is(2 + 5) = 7
. - The key part is make sure if there is a leading “1” after the sum. If the sum has a leading “1”, then the LinkedList should not end.
The Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// create a new linked list that adds two digits and moves on
int sum = 0;
ListNode dummy = new ListNode(-1);
ListNode tail = head;
// loop till both listNodes are pointing to null or sum is 0
while(l1 != null || l2 != null || sum != 0){
if(l1 != null){
sum += l1.val;
l1 = l1.next;
}
if(l2 != null){
sum += l2.val;
l2 = l2.next;
}
tail.next = new ListNode(sum % 10); // get the one's position
sum /= 10; // check to see if there is a leading 1
tail = tail.next; // moves to the next node
}
return dummy.next;
}
}
Time & Space Complexity
- Time Complexity: Since we create a loop so it is
O(n)
. - Space Complexity: Since we use an extra memory which is LinkedList, the Space Complexity is also
O(n)
.