/**
* 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 fast = head.next;
ListNode slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//temp指针是分层两半指针的头指针
ListNode temp = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(temp);
ListNode h = new ListNode(0);
ListNode res = h;
while(left != null && right != null){
if(left.val < right.val){
h.next = left;
left = left.next;
}else{
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left!= null?left:right;
return res.next;
}
}
归并排序