leedcode.21合并两个有序链表

系列文章目录

初识单链表
leedcode.203移除链表元素


文章目录

  • 系列文章目录
  • 方法一:递归
  • 方法二:归并,取小的尾插


将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:
leedcode.21合并两个有序链表_第1张图片
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [ ], l2 = [ ]
输出:[ ]

示例 3:

输入:l1 = [ ], l2 = [0]
输出:[0]

提示:

两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列

方法一:递归

leedcode.21合并两个有序链表_第2张图片
我们以示例1为例子。
leedcode.21合并两个有序链表_第3张图片
leedcode.21合并两个有序链表_第4张图片
leedcode.21合并两个有序链表_第5张图片
这样就可以全部比较完了,升序就完成了。
现在我们已经知道原理了,那么这些结点是怎么连接起来的呢
当程序的递归走到头时,大概形成了这样的千层饼。
leedcode.21合并两个有序链表_第6张图片
然后递归开始return, List 2 的结点4返回上一层递归函数,即List 1 的4结点,于是List 1 结点4的 next就指向List 2 的结点4。

然后是List 2 结点3的 next就指向List 1 的结点4……
这样下去,链表就连接起来了。

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    if(list1 == NULL)
   {
       return list2;
   }

    if(list2 == NULL)
    {
        return list1;
    }

   if(list1->val <= list2->val)
   {
       list1->next = mergeTwoLists(list1->next,list2);
       return list1;
   }
   else
   {
       list2->next = mergeTwoLists(list1,list2->next);
       return list2;
   }

方法二:归并,取小的尾插

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
	//若为空则返回另一个链表
    if(list1 == NULL)
        return list2;
    if(list2 == NULL)
        return list1;

   struct ListNode* head,*tail = NULL;
   head = tail = NULL;

   while(list1 && list2)
   {
       if(list1->val < list2->val)
       {
           if(tail == NULL)
           {
               head = tail = list1;
           }
           else
           {
               tail->next = list1;
               tail = tail->next;
           }
           list1 = list1->next;
       }
       else
       {
             if(tail == NULL)
           {
               head = tail = list2;
           }
           else
           {
               tail->next = list2;
               tail = tail->next;
           }
           list2 = list2->next;
       }
   }
   //当一个链表走完时,尾部与另一个链表连接
   if(list1)
   {
       tail->next = list1;
   }

   if(list2)
   {
       tail->next = list2;
   }
   return head;
}

五一后要认真学习哦。
leedcode.21合并两个有序链表_第7张图片

你可能感兴趣的:(岩浆泉涌C++,链表,数据结构,算法)