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

1. 题目描述

力扣在线OJ——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,因为是链表,所以直接链接过去就好了,不用一个一个搬。

在这里插入图片描述

3.代码实现1

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL) {
        return list2;
    }
    if (list2 == NULL) {
        return list1;
    }
    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 = tail->next;
                }
                cur1 = cur1->next;
        }
        else
        {
              if (head == NULL)
                {
                    head = tail = cur2;//刚开始head==NULL 的时候,先进行赋值,
                }
                else
                {
                    tail->next= cur2;
                    tail = tail->next;
                }
                cur2 = cur2->next;
        }
    }
    if(cur1)
    {
        tail->next = cur1;

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

在这里插入图片描述

4.代码实现2

带哨兵的链表实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    struct ListNode *cur1 = list1, *cur2 = list2;
    struct ListNode *guard = NULL, *tail = NULL;
    guard = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
    tail->next = NULL;
    while (cur1 && cur2) {
        if (cur1->val < cur2->val) {

            tail->next = cur1;
            tail = tail->next;
            cur1 = cur1->next;
        } else {

            tail->next = cur2;
            tail = tail->next;
            cur2 = cur2->next;
        }
    }
    if (cur1) {
        tail->next = cur1;
    }
    if (cur2) {
        tail->next = cur2;
    }
    struct ListNode* head = guard->next;
    free(guard);
    guard = NULL;

    return head;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值