1.新建一个链表,比较顺序尾插
public merge(Node head1,Node head2){
Node result=null;
Node l1=head1;
Node l2=head2;
Node last=null;
while(l1!=null&&l2!=null)
{
if(l1.val<=l2.val)
{
Node next=l1.next;
if(result==null)
{
result=l1;
}
else{
last.next=l1;
}
last=l1;
l1=next;
}//将l1进行尾插
else
{
Node next=l2.next;
if(result==null)
{
result=l2;
}
else{
last.next=l2;
}
last=l2;
l2=next;
}//将p2进行尾插
if(l1!=null)
last.next=l1;//若l1较长,将剩下的结点连到新链表后面
else
last.next=l2;
}
}//合并两个有序链表
2.递归插入,不用新建链表
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);//让l1指向l1的下一个结点与l2的结点中较小的一个
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}