一、题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
二、示例
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
代码实现
链表节点
public class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
ListNode(int val, ListNode listNode) {
this.val = val;
this.next = listNode;
}
}
递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
list.next = mergeTwoList(l1.next, l2);
return l1;
}
l2.next = mergeTwoList(l1, l2.next);
return l2;
}
时间和空间情况
双指针方式
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(listNode1 == null ){
return listNode2;
}
if(listNode2 == null) {
return listNode1;
}
ListNode head = new ListNode(0);
ListNode p = head;
while(listNode1!= null && listNode2!=null){
if(listNode1.val < listNode2.val) {
p.next = listNode1;
listNode1 = listNode1.next;
} else {
p.next = listNode2;
listNode2 = listNode2.next;
}
p = p.next;
}
if (listNode1 != null) {
p.next = listNode1;
}
if (listNode2 != null){
p.next = listNode2;
}
return head.next;
}
时间和空间情况