leetcode 21.合并两个有序链表

⭐️ 往期相关文章

💫链接1:链表中倒数第k个结点(快慢指针问题)
💫链接2:leetcode 876.链表的中间结点(快慢指针问题)
💫链接3:leetcode 206.反转链表
💫链接4:leetcode 203.移除链表元素
💫链接5:数据结构-手撕单链表+代码详解


⭐️ 题目描述

在这里插入图片描述

🌟 leetcode链接:合并两个有序链表

1️⃣
思路1:准备一个新的链表(不带哨兵卫的头),判断两个链表当前结点元素谁小,小的尾插到新的链表。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

/*
    思路1:准备一个新的链表(不带哨兵卫的头),判断两个链表当前结点元素谁小,小的尾插到新的链表。
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){

    // 特殊情况:当一个链表为空,另一个有结点,下面循环进不去。 
    // error:tail = NULL  -> NULL -> next
    if (list1 == NULL) {
        return list2;
    }
    if (list2 == NULL) {
        return  list1;
    }

    struct ListNode* head = NULL;
    // 为当前新链表准备一个尾,方便尾插 不用每次找尾
    struct ListNode* tail = NULL;

    // 遍历两个链表 其中一个链表结束循循环就结束
    while (list1 != NULL && list2 != NULL) {
        if (list1->val < list2->val) {
            // 链表1 < 链表2的情况
            // 把链表1当前结点尾插到新链表
            // 特殊情况:第一次新链表为 NULL
            if (head == NULL) {
                head = tail = list1;
            } else {
                tail->next = list1;
                tail = tail->next;
            }
            // 迭代
            list1 = list1->next;
        } else {
            // 连表2 >= 链表1的情况
            // 把链表2当前结点尾插到新链表
            // 特殊情况:第一次新链表为 NULL
            if (head == NULL) {
                head = tail = list2;
            } else {
                tail->next = list2;
                tail = tail->next;
            }
            list2 = list2->next;
        }
    }
    
    // 来到这里其中一个链表为空 一个链表还有剩余元素
    if (list1) {
        tail->next = list1;
    } else {
        tail->next = list2;
    }


    return head;
}

2️⃣
思路2:准备一个新的链表(带哨兵卫的头),判断两个链表当前结点元素谁小,小的尾插到新的链表。

/*
    思路2:准备一个新的链表(带哨兵卫的头),判断两个链表当前结点元素谁小,小的尾插到新的链表。
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;
    // 哨兵卫的头结点
    head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next = NULL;
    
    // 遍历两个链表 其中一个链表结束循循环就结束
    while (list1 != NULL && list2 != NULL) {
        if (list1->val < list2->val) {
            // 尾插到新链表中
            tail->next = list1;
            tail = tail->next;
            list1 = list1->next;
        } else {
            // 尾插到新链表中
            tail->next = list2;
            tail = tail->next;
            list2 = list2->next;
        }
    }

    // 一个链表为空 一个链表剩余的元素连接到尾处
    if (list1) {
        tail->next = list1;
    } else {
        tail->next = list2;
    }


    return head->next;
}

在这里插入图片描述

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值