将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
Py1:
迭代:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
current = dummy = ListNode(0)
while l1 and l2:
if l1.val<l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 or l2
return dummy.next
原:
在这里稍微讲一下可能初学者不太明白的地方,有三点,一个是while l1 and l2这就话是干嘛的,其实就是说li和l2有空集的时候,也就是比如l1:1,3,5,6,l2:2,3,那么当l1遍历到5时,l2中已经没有值了,那么我们就把剩下的链表直接copy过来就好了,这也就是curr = curr.next的的作用。
还有一点是listnode(0)是什么意思,其实就是相当于为链表加了一个头节点,你可以赋任何值,都不会影响最后合并的效果。如果你理解了这个,那么返回的dummy.next为什么会是我们所需要的答案你也应该知道了。
Py2
递归:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val<l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
Js1
迭代:
/**
* 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) {
let current = new ListNode(-1);
let dummy = current;
while (l1!==null && l2!== null){
if (l1.val<l2.val){
current.next = l1;
l1 = l1.next;
}else{
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 || l2;
return dummy.next
};
Js2
递归:
/**
* 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) {
if (l1 === null){
return l2
}else if(l2 === null){
return l1
}else if(l1.val<l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
};