Last active
March 1, 2019 04:22
-
-
Save userkang/20b7df2c455a523fd5f3fdea688263fc to your computer and use it in GitHub Desktop.
有序链表合并
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 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 | |
}; |
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) { | |
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