The question concerns LeetCode challenge #2:
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 contains a single digit. Add the two numbers and return the sum as a linked list.
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
I compared the following two solutions:
Algorithm with space complexity O(1)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l1Pointer = l1;
ListNode l2Pointer = l2;
while(l1Pointer != null){
if(l2Pointer != null)
l1Pointer.val += l2Pointer.val;
if(l1Pointer.val >= 10){
l1Pointer.val -= 10;
if(l1Pointer.next != null) l1Pointer.next.val++;
else if(l2Pointer != null && l2Pointer.next != null) l2Pointer.next.val++;
else l1Pointer.next = new ListNode(1);
}
if(l1Pointer.next == null && l2Pointer != null && l2Pointer.next != null){
l1Pointer.next = l2Pointer.next;
l2Pointer.next = null;
}
l1Pointer = l1Pointer.next;
if(l2Pointer != null)
l2Pointer = l2Pointer.next;
}
return l1;
}
and it uses more than 39000kb memory:
Algorithm with space complexity O(n)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
and it uses less than 39000kb memory:
I'm very confused. Did I make a mistake in the calculations of the space complexities?