Task
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.
Examples :
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
This problem was taken from Leetcode
Solution
The solution:
Java Script
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ function ListNode(val, next) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { function doSum(a,b, carry) { var result = { val: 0, carry: 0 } var sum = a + b + carry; if(sum > 9) { result.val = sum - 10; result.carry = 1; } else { result.val = sum; result.carry = 0; } return result; } var nodeA = l1; var nodeB = l2; var end = false; var carry = 0; var result = new ListNode(0, null); var resultPointer = result; var tmp = null; while(nodeA != null || nodeB != null) { var valA = nodeA == null ? 0 : nodeA.val; var valB = nodeB == null ? 0 : nodeB.val; var sumResult = doSum(valA, valB, carry); carry = sumResult.carry; resultPointer.val = sumResult.val; resultPointer.next = new ListNode(0, null); tmp = resultPointer; resultPointer = resultPointer.next; nodeA = nodeA ? nodeA.next : null; nodeB = nodeB ? nodeB.next : null; } if(carry != 0) { tmp.next.val = carry; // add carry to the val of the last node } else tmp.next = null; // remove the last empty node. return result; }; var l1 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, null) )) ); var l2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, null) ))))) ) // [9,9,9] , [9,9,9,9,9] // result: [8,9,9,0,0,1] var result = addTwoNumbers(l1, l2); console.log(result);