LeetCode Easy|【21. 合并两个有序链表】

力扣题目链接

状态:拿到本题的第一反应就是使用双指针,分别指向两个链表的开头位置。

随后的思路就是以第一条链表为基准完成插入,并且对于遍历到的每个节点都应该保存其状态。

写了一下代码后发现,我们应该以第一个节点较小的链表作为基准链表。

随后就是开始我们的遍历操作了。

cpp 复制代码
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    	// 其中一个链表为空,直接返回另一个链表
        if (!list1) return list2;
        if (!list2) return list1;
		
		// 确定基准链表
        ListNode* head = nullptr;
        if (list1->val <= list2->val) {
            head = list1;
            list1 = list1->next;
        } else {
            head = list2;
            list2 = list2->next;
        }
		
		// 当前操作指针指向基准链表的头节点
        ListNode* current = head;
	
		// 使用双指针来遍历两个链表
        while(list1 && list2) {
            if (list1->val <= list2->val) {
                current->next = list1;
                list1 = list1->next;
            } else {
                current->next = list2;
                list2 = list2->next;
            }
            current = current->next;
        }
		
		// 最后链接剩余的链表
        if (list1) {
            current->next = list1;
        } else {
            current->next = list2;
        }

        return head;
    }
};

当然了还有一种更加简单的思路,其实思路上主体都是一致的,不过代码上会简单很多,但是他会有一个额外的空间来申请一个新的链表。

cpp 复制代码
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        // 创建一个虚拟头节点
        ListNode dummy(0);
        ListNode* current = &dummy;

        // 使用双指针遍历两个链表
        while (list1 != nullptr && list2 != nullptr) {
            if (list1->val <= list2->val) {
                current->next = list1;
                list1 = list1->next;
            } else {
                current->next = list2;
                list2 = list2->next;
            }
            current = current->next;
        }

        // 连接剩余的链表
        if (list1 != nullptr) {
            current->next = list1;
        } else {
            current->next = list2;
        }

        return dummy.next;
    }
};
相关推荐
洋不写bug几秒前
排序(一)基础排序,插入|希尔|冒泡|直接选择排序详解
java·算法·排序算法·插入排序·冒泡排序·希尔排序·直接选择排序
牧羊人.3332 分钟前
动手学深度学习 03 | 卷积神经网络实现手写数字识别
人工智能·深度学习·神经网络·算法·cnn
AgentMaster26 分钟前
数据治理工具选型指南:一套可复用的四阶段决策框架
大数据·数据结构·人工智能·算法
liliangcsdn44 分钟前
最终留出样本/样本外测试集-holdout解读
算法
爱敲代码的小黄1 小时前
机器学习入门:从数据、训练到业务决策
算法
数据知道1 小时前
哈希与密码存储——bcrypt、Argon2、盐值与彩虹表
网络·算法·安全·网络安全·密码学·哈希算法
haon11221 小时前
树模型在信贷风控怎么用——从决策树到 XGBoost
大数据·人工智能·算法·决策树·机器学习·数据挖掘
wordbaby1 小时前
BM25 是什么?手把手拆解搜索引擎的核心算法
人工智能·算法