Add Two Numbers
https://leetcode.com/problems/add-two-numbers/description/
function ListNode(val) {
this.val = val;
this.next = null;
}
function getLinkedListFromArray(arr) {
const list = new ListNode(0);
let current = list;
for (let el of arr) {
current.next = new ListNode(el);
current = current.next;
}
return list.next;
}
function printLinkedList(head) {
const result = [];
while (head !== null) {
result.push(head.val);
head = head.next;
}
console.log(result.join(' -> '));
}
function addTwoLists(a, b) {
let carry = 0;
let sum = 0;
const head = new ListNode(0);
let now = head;
while (a !== null || b !== null) {
sum = (a ? a.val : 0) + (b ? b.val : 0) + carry;
carry = Math.floor(sum / 10);
now.next = new ListNode(sum % 10);
now = now.next;
a = a ? a.next : null;
b = b ? b.next : null;
}
if (carry) now.next = new ListNode(carry);
return head.next;
}
const l1 = getLinkedListFromArray([1, 2, 3]); // 1 -> 2 -> 3
const l2 = getLinkedListFromArray([2, 3]); // 2 -> 3
printLinkedList(addTwoLists(l1, l2)); // 3 -> 5 -> 3