Created
July 25, 2018 16:26
-
-
Save scwood/3d3e8a8068021a4bd17e8ea2de96cdd4 to your computer and use it in GitHub Desktop.
Merging two sorted lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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