Leetcode21. Merge Two Sorted Lists
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
提交记录
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while(l1!=null&&l2!=null)
{
if(l1.val <= l2.val){
p.next = new ListNode(l1.val);
l1 = l1.next;
}
else{
p.next = new ListNode(l2.val);
l2 = l2.next;
}
p = p.next;
}
if(l1==null) p.next = l2;
if(l2 == null) p.next = l1;
return dummy.next;
}
递归解法
可以如下递归地定义在两个链表里的 merge
操作(忽略边界情况,比如空链表等):
{ L i s t 1 [ 0 ] + m e r g e ( l i s t 1 [ 1 : ] , l i s t 2 ) l i s t 1 [ 0 ] < l i s t 2 [ 0 ] L i s t 2 [ 0 ] + m e r g e ( l i s t 1 , l i s t 2 [ 1 : ] ) o t h e r w i s e } \begin{Bmatrix} List1[0]+merge(list1[1:],list2) &list1[0]<list2[0] \\ List2[0]+merge(list1,list2[1:]) &otherwise \end{Bmatrix} {List1[0]+merge(list1[1:],list2)List2[0]+merge(list1,list2[1:])list1[0]<list2[0]otherwise}
返回值:每一层调用都返回排序好的链表头。
判断 l1
和l2
哪一个的头元素更小,然后递归地决定下一个添加到结果里的值。
Java
public 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;
}
}
}
Python
def mergeTwoLists2(self, l1, l2):
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
- 时间复杂度: O ( m + n ) O(m+n) O(m+n)
- 空间复杂度: O ( m + n ) O(m+n) O(m+n),因为开m+n个栈帧。
迭代解法
我们假设l1
元素严格比 l2
元素少,我们可以将 l2
中的元素逐一插入 l1
中正确的位置。然后维护一个prehead
的哨兵节点,调整它的next指针,让他总是指向l1
与l2
中较小的那个,直到l1
或l2
任一指向null
Java
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// maintain an unchanging reference to node ahead of the return node.
ListNode prehead = new ListNode(-1);
ListNode prev = prehead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
prev.next = l1;
l1 = l1.next;
} else {
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
// exactly one of l1 and l2 can be non-null at this point, so connect
// the non-null list to the end of the merged list.
prev.next = l1 == null ? l2 : l1;
return prehead.next;
}
}
Python
class Solution:
def mergeTwoLists(self, l1, l2):
prehead = ListNode(-1)
prev = prehead
while l1 and l2:
if l1.val <= l2.val:
prev.next = l1
l1 = l1.next
else:
prev.next = l2
l2 = l2.next
prev = prev.next
//可以改成 prev.next = l1 or l2,因为在 Python 中,and 和 or 都有提前截止运算的功能。
prev.next = l1 if l1 is not None else l2
return prehead.next
- 时间复杂度: O ( m + n ) O(m+n) O(m+n)
- 空间复杂度: O ( 1 ) O(1) O(1)