【链表】C010_合并两个有序链表(暴力 / 双指针思想 / 递归)

一、Problem

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

二、Solution

方法一:暴力

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null && l2 == null) {
        return null;
    }
    List<Integer> all = new ArrayList<>();
    ListNode t1 = l1, t2 = l2;
    while (t1 != null) {
        all.add(t1.val);
        t1 = t1.next;
    }
    while (t2 != null) {
        all.add(t2.val);
        t2 = t2.next;
    }
    Collections.sort(all);
    ListNode h =  new ListNode(all.get(0));
    ListNode res = h;
    for (int i = 1; i < all.size(); i++) {
        ListNode t = new ListNode(all.get(i));
        h.next = t;
        h = h.next;
    }
    return res;
}

复杂度分析

  • 时间复杂度: O ( N l o g N ) O(NlogN)
  • 空间复杂度: O ( n ) O(n)

方法二:不动头结点

  • 因为两个链表 l1、l2 是有序的,所以我们可以当成双指针做。
  • 谁比较小,谁移动…
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode dead = new ListNode(-1);
    ListNode cur = dead;
    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            cur.next = l1;
            l1 = l1.next;
        } else {
            cur.next = l2;
            l2 = l2.next;
        }
        cur = cur.next;
    }
    cur.next = l1 == null ? l2 : l1;
    return dead.next;
}

复杂度分析

  • 时间复杂度: O ( N ) O(N)
  • 空间复杂度: O ( 1 ) O(1)

递归

递归是多么优雅啊,高清 Code…

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null || l2 == null)   
    	return l1 == null ? l2 : l1;
    if (l1.val < l2.val) {
        l1.next = mergeTwoLists(l1.next, l2);
        return l1;
    } else {
        l2.next = mergeTwoLists(l1, l2.next);
        return l2;
    }
}
原创文章 787 获赞 314 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105883824