题目描述:
Sort a linked list in O(n log n) time using constant space complexity.
很自然二分法,代码如下:
public ListNode sortList(ListNode head) {
//下面head.next==null不能丢!!
if(head==null||head.next==null)
return head;
int sum=0;
ListNode cur=head;
while(cur!=null){
cur=cur.next;
sum++;
}
int n=sum/2;
ListNode head2=null;
cur=head;
while(n>1){
cur=cur.next;
n--;
}
head2=cur.next;
cur.next=null;
ListNode leftnode=sortList(head);
ListNode rightnode=sortList(head2);
return merge(leftnode, rightnode);
}
public ListNode merge(ListNode listNode1,ListNode listNode2){
if(listNode1==null)
return listNode2;
if(listNode2==null)
return listNode1;
ListNode start=new ListNode(-1),p=start;
while(listNode1!=null&&listNode2!=null){
ListNode newnode;
if(listNode1.val<=listNode2.val){
newnode=new ListNode(listNode1.val);
listNode1=listNode1.next;
}else{
newnode=new ListNode(listNode2.val);
listNode2=listNode2.next;
}
p.next=newnode;
p=p.next;
}
if(listNode1!=null)
p.next=listNode1;
else
p.next=listNode2;
return start.next;
}
1929

被折叠的 条评论
为什么被折叠?



