题目
![题意](https://i-blog.csdnimg.cn/blog_migrate/58a359ec643774242549a31029469c82.png)
思路
- 目前的想法是用两个指针分别指向前面两个链表,用第三个指针指向新链表,然后依次加入,先写写试试
- 写对了,这题不难,让我看看有没有别的方法
- 果然,可以用递归解决,核心在于l.next = mergeList(l.next,R)
题解(双指针)
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode l1 = list1;
ListNode l2 = list2;
ListNode newL = new ListNode();
ListNode pre = newL;
while(l1!=null && l2 !=null ){
if(l1.val == l2.val){
ListNode temp1 = l1.next;
ListNode temp2 = l2.next;
pre.next = l1;
l1.next=l2;
l2.next = null;
pre = l2;
l1 = temp1;
l2 = temp2;
}else if (l1.val < l2.val){
ListNode temp = l1.next;
pre.next = l1;
l1.next = null;
l1 = temp;
pre = pre.next;
}else if (l2.val < l1.val){
ListNode temp = l2.next;
pre.next = l2;
l2.next = null;
l2 = temp;
pre = pre.next;
}
}
if(l1!=null) pre.next = l1;
if(l2!=null) pre.next = l2;
return newL.next;
}
题解(哨兵)
- 使空间复杂度为O(1)
- 就是设立一个新链表表头,连接他们,每次做判断,不开辟新的,故还需要一个哨兵进行判断当前到了哪里。
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode();
ListNode l1 = list1;
ListNode l2 = list2;
ListNode now = head;
while(l1!=null && l2!=null){
if(l1.val==l2.val){
now.next=l1;
now=l1;
l1=l1.next;
now.next=l2;
now=l2;
l2=l2.next;
}else if(l1.val< l2.val){
now.next=l1;
now=l1;
l1=l1.next;
}else{
now.next=l2;
now=l2;
l2=l2.next;
}
}
if(l1==null) now.next=l2;
else if(l2==null) now.next=l1;
return head.next;
}