Closed muregii closed 4 months ago
I tried following the code, but I think I have a simpler to follow solution. Let's break down the problem:
What we know:
input: 2 singly linked lists representing two non-negative integers
output: new linked list with the sum of the inputs
the input is in reverse order, output should also be in reverse order
0 <= Node.val
<= 9
input lists have at least one node but may not be of the same length
guaranteed that the list represents a number that does not have leading zeros
We can match this problem with a temporary head technique. We are creating and returning a new linked list, so we need a way to keep track of the linked list we are creating.
With that in mind, we can develop the following pseudocode:
The code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode temp = new ListNode(0);
ListNode curr = temp;
int carry = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
curr.next = new ListNode(sum % 10);
carry = sum / 10;
curr = curr.next;
l1 = l1.next;
l2 = l2.next;
}
// edge case: uneven lists
while (l1 != null) {
int sum = l1.val + carry;
curr.next = new ListNode(sum % 10);
carry = sum / 10;
curr = curr.next;
l1 = l1.next;
}
while (l2 != null) {
int sum = l2.val + carry;
curr.next = new ListNode(sum % 10);
carry = sum / 10;
curr = curr.next;
l2 = l2.next;
}
// edge case: still have a carry
if (carry > 0) {
curr.next = new ListNode(carry);
}
return temp.next;
}
}
Review of the Solution:
Time complexity: O(n + m)
because we have to traverse through all elements in both linked lists.
Space complexity: O(n
) or O(m)
because the maximum number of digits we need to store is the number of digits in the longer list, plus one more of the temp head.
I hope that helps!
https://github.com/muregii/codeKenya/blob/main/codeK(main)/Leetcode/0002-add-two-numbers/README.md
class Solution { public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
}
Struggling to understand this code. Someone break it down. @muregii