The topic of dry
Merges two ascending lists into a new ascending list and returns. A new list is formed by concatenating all the nodes of a given two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]Copy the code
Example 2:
Input: L1 = [], L2 = [] output: []Copy the code
Source: LeetCode link: leetcode-cn.com/problems/me… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
solution
List merge is actually similar to array merge, we also use double Pointers. Start walking in both lists at the same time. If one side is small, a new node is added until either side of the list has been traversed, so that the rest of the other list is put into the new list.
The thing to notice is that we need to pay attention to the initial head at the beginning.
See the following Js code for details:
Execution time: 64 ms, beating 100.00% of users in all JavaScript commits
Memory consumption: 39.8 MB, beating 7.80% of all JavaScript commits
/** * 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
// point L2 to the next node
l2 = l2.next
} else {
headList = l1
lastList = l1
// point L1 to the next node
l1 = l1.next
}
// Define a loop to loop through two lists and add elements
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
};
Copy the code