将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路:
1.添加一个哨兵节点,用l2,l2分别指向链表的开头
2.比较两者中较小的那个,将其放入新链表中
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
var mergeTwoLists = function(l1, l2) {
let prehead = new ListNode(-1)
let pre = prehead
if(l1==null) return l2
if(l2==null) return l1
while(l1 && l2){
if(l1.val>=l2.val){
prehead.next = l2
l2 = l2.next
}else{
prehead.next = l1
l1 = l1.next
}
prehead = prehead.next
}
prehead.next= l1===null?l2:l1
return pre.next
};
``