题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
if(head == null || head.next == null)
return head;
ListNode slow=head,fast=head.next;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode temp=slow.next;
slow.next=null;//分割
ListNode l=sortInList(head);
ListNode r=sortInList(temp);
ListNode newHead=new ListNode(-1);
ListNode list=newHead;
while(l!=null&&r!=null){
if(l.val<r.val){
list.next=l;
l=l.next;
}
else{
list.next=r;
r=r.next;
}
list=list.next;
}
list.next = l != null ? l : r;
return newHead.next;
}
}