/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = null, slow = head, fast = head;
while(fast!=null && fast.next!=null)
{
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
pre.next = null;
ListNode left = sortList(head);
ListNode right = sortList(slow);
return merge(left,right);
}
private ListNode merge(ListNode left, ListNode right) {
ListNode dummyHead = new ListNode(-1);
ListNode p = dummyHead;
while(left!=null && right!=null)
{
if(left.val < right.val)
{
p.next = new ListNode(left.val);
p = p.next;
left = left.next;
}
else
{
p.next = new ListNode(right.val);
p = p.next;
right = right.next;
}
}
if(left!=null)
{
p.next = left;
}
if(right!=null)
{
p.next = right;
}
return dummyHead.next;
}
}
数组的归并排序