• 【数据结构入门_链表】 Leetcode 21. 合并两个有序链表


    原题连接: Leetcode 21. Merge Two Sorted Lists

    You are given the heads of two sorted linked lists list1 and list2.

    Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

    Return the head of the merged linked list.

    Example 1:
    在这里插入图片描述

    Input: list1 = [1,2,4], list2 = [1,3,4]
    Output: [1,1,2,3,4,4]
    
    • 1
    • 2

    Example 2:

    Input: list1 = [], list2 = []
    Output: []
    
    • 1
    • 2

    Example 3:

    Input: list1 = [], list2 = [0]
    Output: [0]
    
    • 1
    • 2

    Constraints:

    • The number of nodes in both lists is in the range [0, 50].
    • -100 <= Node.val <= 100
    • Both list1 and list2 are sorted in non-decreasing order.

    方法一:迭代

    思路:

    先建立一个虚拟头结点prehead,和一个指向虚拟头结点的指针prev。返回的时候返回prehead->head就可以,能减少很多麻烦的边界问题。
    两个指针遍历两个链表。每次选择关键字小的结点接到prev上即可。
    注意最后需要扫尾,把循环结束没遍历完的链表的余下部分直接接上去。
    这个扫尾的思想用的太多了,类似于归并排序

    c++代码:

    /**
     * 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) {
            // 创建虚拟头结点prehead, 值为-1    prev为指向虚拟头结点的指针
            ListNode* preHead = new ListNode(-1);
            ListNode* prev = preHead;
    
            // 双指针遍历两个链表
            while(list1 != nullptr && list2 != nullptr){
                // 找到小的结点
                if(list1->val < list2->val){
                    prev->next = list1;
                    list1 = list1->next;
                } else {
                    prev->next = list2;
                    list2 = list2->next;
                }
                prev = prev->next;
            }
            
            // 扫尾
             prev->next = (list1 == nullptr ? list2 : list1);
    
            return preHead->next;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    复杂度分析:

    • 时间复杂度:O(m+n),需要遍历两个链表的所有元素
    • 空间复杂度:O(1),常数个临时变量
  • 相关阅读:
    设计模式-原型模式
    【K8S】K8S服务搭建
    2022年最新四川交安安全员考试模拟题库及答案
    Java设计模式-抽象工厂模式
    一眼万年,4款逆天好用的宝藏软件,内存爆满也不舍得卸载
    QT使用sqllite
    查看docker资源占用,及释放资源
    MySQL——存储引擎
    `SpringBoot`+`axios`结合发送`ajax`请求
    脉冲编码器A、B、Z相正余弦波转换为RS-485输出
  • 原文地址:https://blog.csdn.net/cwtnice/article/details/125536529