题干
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/me… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法
链表的归并实际上和数组的归并是相似的,我们同样使用双指针。同时在两个链表开始走。遇到一方小的则添加进新的节点,知道有任意一方链表遍历 完成,这样将另一个的链表的剩余的部分全部放入新的链表中。
需要注意的是我们需要留意刚开始时候的起始head。
详细操作请看下面Js代码:
执行用时:64 ms, 在所有 JavaScript 提交中击败了100.00%的用户
内存消耗:39.8 MB, 在所有 JavaScript 提交中击败了7.80%的用户
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @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;
let headList = null
let lastList = null
if (l1.val > l2.val) {
headList = l2
lastList = l2
// 将l2指向下一个节点
l2 = l2.next
} else {
headList = l1
lastList = l1
// 将l1指向下一个节点
l1 = l1.next
}
// 定义循环用于循环两个链表并且添加元素
while (l1 != null && l2 != null) {
if (l1.val > l2.val) {
lastList.next = l2
lastList=lastList.next
l2 = l2.next
} else {
lastList.next = l1
lastList=lastList.next
l1 = l1.next
}
}
if(l2==null){
lastList.next=l1
}else{
lastList.next=l2
}
return headList
};