合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

解题思路1:链表迭代实现

当两个链表都不为空时,迭代判断大小,添加节点。一方为空,则直接补另一方剩下所有的节点。
时间复杂度取决于两个链表长度,O(m+n)。
空间复杂度小,只需要修改指针指向性,O(1)

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 判断头
        ListNode pre = new ListNode(-1);
        ListNode cur = pre;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                cur.next = list1;
                list1 = list1.next;
                cur = cur.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
                cur = cur.next;
            }
        }
        // 剩下的不循环
        cur.next = list1 != null ? list1 : list2;
        return pre.next;
    }

使用递归思想实现

递归要考虑终止条件、子集等。终止条件,当某一个链表到达末尾,递归就可以结束了。
针对于子集,假设list1是1,2,4,list2是1,3,4,当递归一层后,子集变为list1=2,4,list2=1,3,4.

class Solution {
    public static 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;
        }
    }
}
posted @ 2022-02-22 08:09  Awecoder  阅读(117)  评论(0编辑  收藏  举报