描述
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
例子
思路
- 迭代 O(n)
申请个头结点,遍历两个链表的结点,每次找出最小的结点,放在新链表后面,然后将较小结点所在链表的下一个结点和之前较大结点进行比较
- 递归:func作用是把两个递增的链表排成一个。 O(n)
-
每次调用,先选出较小的结点,然后将其后面的排好序,返回较小结点为开头的排好序的链表
答案
- python
*迭代*
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
cur = head
while l1 and l2:
if l1.val<l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
cur.next=l1 or l2
# 取代 if l1:cur.next=l1 if l1:cur.next=l2
return head.next
*递归*
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
#l1 or l2为空时
if l1 is None or l2 is None:
return l1 or l2
#比较两个链表的当下结点,选出较小的,并递归得到剩下的结点中最小的。两个结点一个单位
if l1.val <l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
- java
#boss创公司,boss的分身clone,一个市场,一个市场的开拓
#给两个有序链表排序,两个老总亲自下场,老总总是向前走,停在所站位置比较后,各自最小的地方(走过的不算了)
ListNode head = new ListNode(-1);
ListNode cur=head;
while(l1!=null && l2!=null) {
if(l1.val<=l2.val) {
cur.next=l1;
l1 = l1.next;
}else{
cur.next=l2;
l2=l2.next;
}
cur=cur.next;
}
if(l1!=null) cur.next=l1;
if(l2!=null) cur.next=l2;
return head.next;
#递归
class Solution {
//接受两个递增链表,返回排好序的链表
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
if(l1.val<=l2.val) {
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}
//else
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
- c++
*迭代*
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode(0);
ListNode* cur = head;
while (l1 && l2)
{
if (l1->val<l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1?l1:l2;
/* 取代
if (l1) cur->next = l1;
if (l2) cur->next = l2;
*/
return head->next;
}
*递归*
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1)
return l2;
if (!l2)
return l1;
if (l1->val<l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;//
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
将两个正序链表,合并成降序
头插入
ListNode h = new ListNode(-1);
while(l1!=null || l2!=null) {
int a = l1==null?Integer.MAX_VALUE:l1.val;
int b = l2==null?Integer.MAX_VALUE:l2.val;
if(a<b){//l1肯定不是null
ListNode temp = l1.next;
l1.next=h.next;
h.next=l1;
l1=temp;
}else{//l2肯定不是null
ListNode temp = l2.next;
l2.next=h.next;
h.next=l2;
l2=temp;
}
}
return h.next;