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
Analysis:
- Initialize current node to dummy head of the returning list.
- Initialize carry to 00.
- Initialize pp and qq to head of l1l1 and l2l2 respectively.
- Loop through lists l1l1 and l2l2 until you reach both ends.
- Set xx to node pp‘s value. If pp has reached the end of l1l1, set to 00.
- Set yy to node qq‘s value. If qq has reached the end of l2l2, set to 00.
- Set sum = x + y + carrysum=x+y+carry.
- Update carry = sum / 10carry=sum/10.
- Create a new node with the digit value of (summod10)(summod10) and set it to current node’s next, then advance current node to next.
- Advance both pp and qq.
- Check if carry = 1carry=1, if so append a new node with digit 11 to the returning list.
- Return dummy head’s next node.
Time complexity: O(max(m, n))
Space complexity: O(max(m, n))
Code is below:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // O(n) O(1) if (l1 == null || l2 == null) { return null; } ListNode dummy = new ListNode(0); ListNode cur = dummy; int sum = 0; int carry = 0; while (l1 != null || l2 != null) { int num1 = l1 == null ? 0 : l1.val; int num2 = l2 == null ? 0 : l2.val; sum = num1 + num2 + carry; // update the next node cur.next = new ListNode(sum % 10); cur = cur.next; carry = sum / 10; l1 = l1 == null ? null : l1.next; l2 = l2 == null ? null : l2.next; } // Check the last corner case if (carry != 0) { cur.next = new ListNode(carry); } return dummy.next; } }