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.
LeetCode-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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
We can solve this problem using a simple iterative approach for traversing linked lists.
carry
.Here is a Java implementation of the above approach:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode itr = dummy;
int carry = 0;
while (l1 != null || l2 != null) {
int x = (l1 != null) ? l1.val : 0;
int y = (l2 != null) ? l2.val : 0;
int sum = carry + x + y;
carry = sum / 10;
itr.next = new ListNode(sum % 10);
itr = itr.next;
if (l1 != null){
l1 = l1.next;
}
if (l2 != null){
l2 = l2.next;
}
}
if (carry > 0) {
itr.next = new ListNode(carry);
}
return dummy.next;
}
The time complexity for this approach is $O(max(m, n))$, where $m$ and $n$ are the lengths of the two linked lists.
Be notified of new posts. Subscribe to the RSS feed.