Skip to content

Instantly share code, notes, and snippets.

@userkang
Last active March 1, 2019 04:22
Show Gist options
  • Save userkang/20b7df2c455a523fd5f3fdea688263fc to your computer and use it in GitHub Desktop.
Save userkang/20b7df2c455a523fd5f3fdea688263fc 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 mergeTwoLists = function(l1, l2) {
var head = new ListNode(0)
var curr = head
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
curr.next = l1
l1 = l1.next
} else {
curr.next = l2
l2 = l2.next
}
curr = curr.next
}
if (l1 === null) {
curr.next = l2
}
if (l2 === null) {
curr.next = l1
}
return head.next
};
/**
* 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) {
if (l1 === null && l2 === null) return null
if (l1 === null) return l2
if (l2 === null) return l1
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2)
return l1
} else {
l2.next = mergeTwoLists(l1, l2.next)
return l2
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment