Skip to content

Instantly share code, notes, and snippets.

@scwood
Created July 25, 2018 16:26
Show Gist options
  • Save scwood/3d3e8a8068021a4bd17e8ea2de96cdd4 to your computer and use it in GitHub Desktop.
Save scwood/3d3e8a8068021a4bd17e8ea2de96cdd4 to your computer and use it in GitHub Desktop.
Merging two sorted lists
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
var result = {next: null}
var prev = result;
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
prev.next = l1 ? l1 : l2;
return result.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment