Description
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
Thinking Process
- The question is straightforward, the trick is how to create and store the new result
- Create a virtual head that will not be returned (only as a pointer to the listnode to be returned)
- Traverse through the two list, create new ListNode only when there is need to do so (l1 != null or l2 != null or carry == 1)
- Return the next node of the virtual head (where the result really starts)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode head = new ListNode(0);
ListNode headCopy = head;
while(l1 != null || l2 != null || carry == 1){
int num1 = (l1 == null) ? 0 : l1.val;
int num2 = (l2 == null) ? 0 : l2.val;
int sum = num1 + num2 + carry;
if(sum < 10){
ListNode current = new ListNode(sum);
headCopy.next = current;
headCopy = current;
carry = 0;
}else{
ListNode current = new ListNode(sum - 10);
headCopy.next = current;
headCopy = current;
carry = 1;
}
l1 = (l1 == null) ? null : l1.next;
l2 = (l2 == null) ? null : l2.next;
}
return head.next;
}
Complexity
- Two linkedlists need to be traversed exactly once, the time complexity is hence O(n)
- Space complexity is O(n) for storing the result