Skip to content

Instantly share code, notes, and snippets.

@anjanesh
Created November 7, 2025 13:07
Show Gist options
  • Save anjanesh/cc5e376588d1eb8150c4c0b4efe3c090 to your computer and use it in GitHub Desktop.
Save anjanesh/cc5e376588d1eb8150c4c0b4efe3c090 to your computer and use it in GitHub Desktop.
/**
* 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 result = new ListNode();
let n = result;
let carry = 0;
let noMoreL1 = false, noMoreL2 = false;
do
{
let v1 = 0, v2 = 0;
if (l1) v1 = l1.val;
if (l2) v2 = l2.val;
let sum = v1 + v2 + carry;
if (sum >= 10)
{
n.val = sum % 10;
carry = 1;
}
else
{
n.val = sum;
carry = 0;
}
if (l1 && !l1.next) noMoreL1 = true;
if (l2 && !l2.next) noMoreL2 = true;
if ((l1 && l1.next) || (l2 && l2.next) || carry == 1)
{
n.next = new ListNode();
n = n.next;
if (noMoreL1 && noMoreL2) n.val = 1;
}
if (noMoreL1 && noMoreL2) break;
if (l1 && l1.next) l1 = l1.next; else l1 = null;
if (l2 && l2.next) l2 = l2.next; else l2 = null;
} while (true);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment