初阶数据结构习题【7】(3顺序表和链表)—— 21. 合并两个有序链表

1. 题目描述

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

示例1
初阶数据结构习题【7】(3顺序表和链表)—— 21. 合并两个有序链表_第1张图片
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:
输入:l1 = [], l2 = []
输出:[]

示例 3:
输入:l1 = [], l2 = [0]
输出:[0]

2. 思路

合并两个链表和合并两个数组的最简单思路都一样的,都是从两个表中比较元素,谁小就放到新的表中;

  1. 定义newhead = NULL,tail = NULL; newhead 是新链表的头,tail是新链表的尾部;
  2. 比较cur1->val 和 cur2->val ,谁小就谁插入newhead的尾巴tail->next中;
  3. tips1:第一次插入的时候,头插的逻辑要单独处理,因为tail == NULL,无法使用tail->next;
  4. tips2:cur1和cur2比较到尾时候,谁先结束到尾,还没到尾的,直接把剩下的链表插入到newhead链表中,即tail->next,因为是链表,所以直接链接过去就好了,不用一个一个搬。

初阶数据结构习题【7】(3顺序表和链表)—— 21. 合并两个有序链表_第2张图片

3.代码实现

这个版本代码,在力扣中跑不过,报超出时间限制。

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

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

    while (cur1&&cur2) {//有一个结束就结束了,我们写的是继续的条件,两个都不为空才是我们的继续条件

        if (cur1->val < cur2->val) {
                if (head == NULL)
                {
                    head = tail = cur1;
                }
                else
                {
                    tail->next= cur1;
                    tail = cur1->next;
                }
                cur1 = cur1->next;
        }
        else
        {
              if (head == NULL)
                {
                    head = tail = cur2;
                }
                else
                {
                    tail->next= cur2;
                    tail = cur2->next;
                }
                cur2 = cur2->next;
        }
    }
    if(cur1)
    {
        tail->next = cur1;

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

你可能感兴趣的:(#,#,Leetcode,数据结构,链表)