持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天。
题目链接: leetcode.com/problems/me…
1.题目介绍(合并两个排序链表)
You are given the heads of two sorted linked lists list1 and list2.
【Translate】: 已知两个排序链表list1和list2的表头。
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
【Translate】: 将两个列表合并成一个排序列表。列表应该通过将前两个列表的节点拼接在一起来创建。
Return the head of the merged linked list.
【Translate】: 返回合并的链表的头。
【测试用例】:
【约束】:
2. 题解
2.1 Iterative solution -- O(n)
davidluoyes提供的题解。思路很简单,就是让当前list1.val与list2.val进行对比,谁小就让n2.next指向谁。最后再判断一下是list1先空了还是list2先空了,然后指向相应的元素即可。
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
else if (list2 == null) return list1;
ListNode n1 = new ListNode(0);
ListNode n2 = n1;
while (list1 != null && list2 != null)
{
if (list1.val < list2.val)
{
n2.next = list1;
list1 = list1.next;
}
else
{
n2.next = list2;
list2 = list2.next;
}
n2 = n2.next;
}
n2.next = list1 != null ? list1 : list2;
return n1.next;
}
2.2 Recursion solution -- O(n)
yangliguang所给出的Java, 1 ms, 4 lines codes, using recursion题解。利用了递归的思想,通过判断条件,如此递归下去就知道最后没有了,递归结束。
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;
}
}