题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/*
* 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 fast = head.next;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode flu = slow.next;
slow.next = null;
ListNode left = sortInList(head);
ListNode right = sortInList(flu);
ListNode node = new ListNode(-1);
ListNode pre = node;
while(left != null && right != null){
if(left.val < right.val){
pre.next = left;
left = left.next;
}else{
pre.next = right;
right = right.next;
}
pre = pre.next;
}
if(left != null){
pre.next = left;
}else{
pre.next = right;
}
return node.next;
}
}
查看8道真题和解析
