2.21 Add Two Numbers
Description
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
Method
Since numbers is represented in reverse order by linkedlist, we just need to add numbers from the both heads to tails.
So we need a int add for store the add digit if the sum of two digits larget than 10;
and if one list is short, we need do loop the other one's remain nodes;
Time and Space Complexity
o(n + m)
Code
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null){
return l1 == null ? l2 : l1;
}
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
int add = 0;
while (l1 != null && l2 != null){
int v = (l1.val + l2.val + add) % 10;
ListNode node = new ListNode(v);
add = (l1.val + l2.val + add) / 10;
pre.next = node;
pre = pre.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null){
int v = (l1.val + add) % 10;
ListNode node = new ListNode(v);
add = (l1.val + add) / 10;
pre.next = node;
pre = pre.next;
l1 = l1.next;
}
while (l2 != null){
int v = (l2.val + add) % 10;
ListNode node = new ListNode(v);
add = (l2.val + add) / 10;
pre.next = node;
pre = pre.next;
l2 = l2.next;
}
if (add > 0){
pre.next = new ListNode(add);
}
return dummy.next;
}
}