将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
说明:
S
中仅包含大小写字母和空格。单词间有且仅有一个空格。1 <= S.length <= 150
。
/**
* 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 mergeTwoLists = function(l1, l2) {
function ListNode(val) {
this.val = val;
this.next = null;
}
if(l1 === null && l2 === null){
return null;
}else{
var result = null,
arr = [],
node = null;
//取出l1的所有值
while(l1 !== null){
arr.push(l1.val)
l1 = l1.next;
}
//取出l2的所有值
while(l2 !== null){
arr.push(l2.val)
l2 = l2.next;
}
//排序
arr.sort((a,b) => a - b);
//构建链表
result = new ListNode(arr.shift());
node = result;
while(arr.length !== 0){
node.next = new ListNode(arr.shift());
node = node.next;
}
return result;
}
};