一、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;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:不动头结点
- 因为两个链表 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;
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
递归
递归是多么优雅啊,高清 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;
}
}