I have the following code and spent 6 hours trying to solve without luck. It gets stuck with LinkedList of 1 -> 8, 0 -> null as the input. My output is just 1 -> null and I'm not sure why. I tried to follow through my code manually and it should create new "next = {val: 8, next: null}", but it isn't happening...
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const traversal = function(l1, l2, s, n) {
if (l1 !== null && l2 !== null) {
n.val = l1.val + l2.val + s;
} else if (l1 !== null && l2 === null && !s) {
n.val = l1.val + s;
} else if (l1 === null && l2 !== null && !s) {
n.val = l2.val + s;
} else if (l1 === null && l2 === null && s) {
n.val = s
}
s = 0;
if (n.val > 9) {
s = Number(n.val.toString()[0])
n.val = Number(n.val.toString()[1])
}
if (l1 === null && l2 === null && !s) {
return;
}
if (l1 !== null && l2 !== null && l1.next && l2.next) {
n.next = new ListNode
traversal(l1.next, l2.next, s, n.next)
} else if (l1 !== null && l2 === null && l1.next !== null && l2.next === null) {
n.next = new ListNode
traversal(l1.next, null, s, n.next)
} else if (l1 === null && l2 !== null && l1.next === null && l2.next !== null) {
n.next = new ListNode
traversal(null, l2.next, s, n.next)
} else if (l1.next === null && l2.next === null && s) {
n.next = new ListNode
traversal(null, null, s, n.next)
}
}
var addTwoNumbers = function(l1, l2) {
let storage = 0;
const result = new ListNode
traversal(l1, l2, storage, result)
//console.log(result.next)
return result
};
new ListNode(0). It's important that you use the parentheses to invoke the constructor function, and pass any necessary parameters. I'm trying to get it to work right now, but maybe you can shed more light on what your addTwoNumbers function is expecting as parameters?