Skip to content

Instantly share code, notes, and snippets.

@197291
Created May 5, 2019 05:44
Show Gist options
  • Save 197291/1c296773c1726b13490fbd565340db7c to your computer and use it in GitHub Desktop.
Save 197291/1c296773c1726b13490fbd565340db7c to your computer and use it in GitHub Desktop.
/**
* 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) {
let cur = new ListNode(0), dummy = new ListNode(0), carry = 0;
dummy.next = cur;
while (l1 || l2 || carry !== 0) {
let sum = carry + (l1 === null ? 0 : l1.val) + (l2 === null ? 0 : l2.val);
l1 = l1 === null ? null : l1.next;
l2 = l2 === null ? null : l2.next;
carry = (sum >= 10 ? 1 : 0);
cur.next = new ListNode(sum % 10);
cur = cur.next;
}
return dummy.next.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment