leetcode刷题篇 21题合并两个排序的链表 java C++版本

题目放一下:
在这里插入图片描述
思路分析:
举例分析一波:
在这里插入图片描述
l1和l2是要合并的两个链表,m是最后组合而成的链表

上代码:
首先是C++的
使用链表:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* tail = &dummy;
        while(l1 && l2) {
            if (l1->val < l2->val) {
                tail->next = l1;
                l1 = l1->next;
            } else {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        } 
        if (l1) tail->next = l1;
        if (l2) tail->next = l2;
        return dummy.next;
    }
};

在这里插入图片描述
如果使用递归的话:
merge(a, b)
= a if b is empty
= b if a is empty
=a[0] + merge(a[1], b) if a[0] < b[0]
=b[0] + merge(a, b[1]) if a[0] > b[0]

使用递归:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode dummy(0);
        ListNode* tail = &dummy;
        while(l1 && l2) {
            if (l1->val < l2->val) {
                tail->next = l1;
                l1 = l1->next;
            } else {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        } 
        if (l1) tail->next = l1;
        if (l2) tail->next = l2;
        return dummy.next;
    }
};

在这里插入图片描述
然后是java的
使用链表

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode l3 = new ListNode(0);
        ListNode tail = l3;
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        while ((l1 != null) && (l2 != null)) {
            if (l1.val < l2.val) {
                tail.next = l1;
                l1 = l1.next;
            } else {
                tail.next = l2;
                l2 = l2.next;
            }
            tail = tail.next;
        }
        if (l1 == null) {
            tail.next = l2;
        }
        if (l2 == null) {
            tail.next = l1;
        }
        return l3.next;
    }
}

在这里插入图片描述
使用递归方法:

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

在这里插入图片描述

时间复杂度分析:
使用链表的话
T(n) = 1 + T(n-1)
= O(n)

使用数组的话
T(n) = n + T(n-1)
= O(n^2)

这篇文章的C++版是参照B站的up主花花酱老师的视频写的,java版是我自己写的,有兴趣可以关注花花酱老师,讲的很好~

猜你喜欢

转载自blog.csdn.net/weixin_45806131/article/details/108432863