合并两个已经排好序的链表,注意需要用已有的节点组成新链表。这题与第4题很相似。
合并两个数组如下
var newArray = []
function merge(el) {
newArray.push(el)
}
while (true) {
if (nums1[a] < nums2[b]) {
merge(nums1[a])
a++
continue
}
if (nums2[b] < nums1[a]) {
merge(nums2[b])
b++
continue
}
if (a < nums1.length) {
merge(nums1[a])
a++
continue
}
if (b < nums2.length) {
merge(nums2[b])
b++
continue
}
return newArray
}
合并两个链表差不多
var mergeTwoLists = function(l1, l2) {
var dummy = new ListNode, node = dummy
while(true){
if (l1 && l2){
if (l1.val <= l2.val) {
node = node.next = l1;
l1 = l1.next
} else {
node = node.next = l2;
l2 = l2.next
}
continue
}
if(!l2 && l1){
node = node.next = l1
l1 = l1.next
continue
}
if(!l1 && l2){
node = node.next = l2
l2 = l2.next
continue
}
return dummy.next
}
return dummy.next
};