leetcode_21 合并两个有序链表

1. 题意

合并两个有序链表。

2. 题解

2.1 递归

如果其中一个链表为空了,就直接返回另一个链表的头节点。

如果两个都不空,则取其中较小的链表头节点。再递归处理剩下的链表。

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, 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;
        }
    }
};
2.2 迭代

可以用一个头节点来减少复杂度。

同时我们只需要维护新链表的尾节点即可。

我们在循环中处理两个链表均非空的情况,当处理完成后最多只有一个

链表非空了再单独处理一下就好了。

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        
        auto dumpNode = make_shared<ListNode>(-1);

        ListNode *tail = dumpNode.get();

        while ( list1 && list2 ) {
            if ( list1->val < list2->val ) {
                tail->next = list1;
                tail = list1;
                list1 = list1->next;
            }
            else {
                tail->next = list2;
                tail = list2;
                list2 = list2->next;
            }
        }

        tail->next = list1 == NULL ? list2 : list1;
        
        
        return dumpNode->next;
    }
};

3. 参考

leetcode

相关推荐
mark-puls2 小时前
C语言打印爱心
c语言·开发语言·算法
Python技术极客2 小时前
将 Python 应用打包成 exe 软件,仅需一行代码搞定!
算法
吃着火锅x唱着歌2 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun2 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌2 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
我星期八休息3 小时前
深入理解跳表(Skip List):原理、实现与应用
开发语言·数据结构·人工智能·python·算法·list
lingran__3 小时前
速通ACM省铜第四天 赋源码(G-C-D, Unlucky!)
c++·算法
haogexiaole3 小时前
贪心算法python
算法·贪心算法
希望20173 小时前
图论基础知识
算法·图论