Skip to content

Instantly share code, notes, and snippets.

@carl-parrish
Created December 11, 2017 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carl-parrish/73a28e22d7c02f11e1ddd790b269a33b to your computer and use it in GitHub Desktop.
Save carl-parrish/73a28e22d7c02f11e1ddd790b269a33b to your computer and use it in GitHub Desktop.
Add Two Linked List.

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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2, carry = 0) {
  if (l1 === null && l2 === null && carry === 0) return null;

  let val = carry;

  val += l1 !== null ? l1.val : 0;
  val += l2 !== null ? l2.val : 0;

  var result = new ListNode(val % 10);

  result.next = addTwoNumbers(
    l1 === null ? null : l1.next,
    l2 === null ? null : l2.next,
    val >= 10 ? 1 : 0
  );

  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment