题目地址这里
归并排序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null&&l2==null)
{
return null;
}
if(l1==null&&l2!=null)
{
return l2;
}
if(l1!=null&&l2==null)
{
return l1;
}
//l1!=null&&l2!=null
ListNode result;
if(l1.val<l2.val)
{
result=l1;
l1=l1.next;
}
else
{
result=l2;
l2=l2.next;
}
ListNode resultPoint=result;
while(l1!=null&&l2!=null)
{
if(l1.val<l2.val)
{
resultPoint.next=l1;
resultPoint=l1;
l1=l1.next;
}
else
{
resultPoint.next=l2;
resultPoint=l2;
l2=l2.next;
}
}
if(l1==null)
{
resultPoint.next=l2;
}
else
{
resultPoint.next=l1;
}
return result;
}
}