Why does my linked list solution fail when I make my code more modular?
I am tackling question 2 on Leetcode "Add 2 numbers" in linked list format.
Here is the question:
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.
I have a working solution with repetitive code. When I abstract out the body of my last two functions into a reusable function, my solution fails. Why is this?
One assumption I am making is that linked list nodes are objects and should therefore be passed by reference. At least in JavaScript.
Here is my solution that succeeds (before making the code more modular)...
var addTwoNumbers = function(l1, l2) {
let l3 = new ListNode(0, null);
let head = l3;
let carry = 0;
while (l1 != null && l2 != null) {
l3.next = new ListNode(carry, null);
l3 = l3.next;
let sum = l1.val + l2.val + l3.val;
let ones = sum % 10;
carry = Math.floor(sum / 10);
l3.val = ones;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
l3.next = new ListNode(carry, null);
l3 = l3.next;
let sum = l1.val + l3.val;
let ones = sum % 10;
carry = Math.floor(sum / 10);
l3.val = ones;
l1 = l1.next;
}
while (l2 != null) {
l3.next = new ListNode(carry, null);
l3 = l3.next;
let sum = l2.val + l3.val;
let ones = sum % 10;
carry = Math.floor(sum / 10);
l3.val = ones;
l2 = l2.next;
}
if (carry == 1) {
l3.next = new ListNode(carry, null);
}
return head.next;
};
Here is my solution that fails...
/**
* Definition for singly-linked list.
* 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) {
let l3 = new ListNode(0, null);
let head = l3;
let carry = 0;
while (l1 != null && l2 != null) {
l3.next = new ListNode(carry, null);
l3 = l3.next;
let sum = l1.val + l2.val + l3.val;
let ones = sum % 10;
carry = Math.floor(sum / 10);
l3.val = ones;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
carry = addRemainingNodes(l1, l3, carry);
}
while (l2 != null) {
carry = addRemainingNodes(l2, l3, carry);
}
if (carry == 1) {
l3.next = new ListNode(carry, null);
}
return head.next;
};
function addRemainingNodes(la, lb, carry) {
lb.next = new ListNode(carry, null);
lb = lb.next;
let sum = la.val + lb.val;
let ones = sum % 10;
carry = Math.floor(sum / 10);
lb.val = ones;
la = la.next;
return carry;
}