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

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50] -100 <= Node.val <= 100l1和l2均按 非递减顺序 排列
模拟做法:
通过判断每个节点的大小关系,模拟前后位置,当某一个为空的时候,只要接上另外一个即可。复杂度O(n+m)
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode root = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
head.next = list1;
list1 = list1.next;
}
else {
head.next = list2;
list2 = list2.next;
}
head = head.next;
}
while (list1 != null) {
head.next = list1;
list1 = list1.next;
head = head.next;
}
while (list2 != null) {
head.next = list2;
list2 = list2.next;
head = head.next;
}
return root.next;
}
优化:
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode root = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
head.next = list1;
list1 = list1.next;
}
else {
head.next = list2;
list2 = list2.next;
}
head = head.next;
}
if (list1 != null) {
head.next = list1;
}
if (list2 != null) {
head.next = list2;
}
return root.next;
}
递归做法:
优化模拟步骤,原理相同。复杂度O(n+m)
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
if(list1.val >= list2.val){
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
else{
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}
}
No responses yet