Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 05:27
Show Gist options
  • Save pjcodesjs/6261df51dde60f7c9170d94304acfa5d to your computer and use it in GitHub Desktop.
Save pjcodesjs/6261df51dde60f7c9170d94304acfa5d to your computer and use it in GitHub Desktop.
function addTwoNumbers(l1, l2) {
let carry = 0;
let result = new ListNode(0);
let current = result;
while (l1 || l2) {
let sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
carry = sum >= 10 ? 1 : 0;
current.next = new ListNode(sum % 10);
current = current.next;
if (l1) l1 = l1.next;
if (l2) l2 = l2.next;
}
if (carry) {
current.next = new ListNode(1);
}
return result.next;
}
// Assuming that the linked list nodes are represented by the following class:
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
// You can call the function by creating two linked lists and passing them as arguments:
let l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
let l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
let result = addTwoNumbers(l1, l2);
console.log(result); // should print: ListNode { val: 7, next: ListNode { val: 0, next: ListNode { val: 8, next: null } } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment