链表
链表-归并排序1
class Solution {
private ListNode mergeSort(ListNode head, ListNode tail) {
if (head == null) {
return null;
}
if (head.next == tail) {
head.next = null ;
return head;
}
ListNode slow = head; ListNode fast = head;
while (fast != tail) {
slow = slow.next;
fast = fast.next;
if (fast != tail) {
fast = fast.next;
}
}
ListNode mid = slow;
ListNode left = mergeSort(head, mid );
ListNode right = mergeSort(mid, tail);
return merge(left, right);
}
private ListNode merge(ListNode left , ListNode right) {
ListNode vir = new ListNode();
ListNode cu = vir;
while (left != null && right != null) {
if (left.val <= right.val) {
cu.next = left;
left = left.next;
} else {
cu.next = right;
right = right.next;
}
cu = cu.next;
}
if (left != null) {
cu.next = left;
} else if (right != null) {
cu.next = right;
}
return vir.next;
}
public ListNode sortList(ListNode head) {
return mergeSort(head, null);
}
}