链表排序之归并排序:
public static ListNode mergeSortList(ListNode head){
if (null == head || null == head.next){
return head;
}
ListNode slow = head;
ListNode fast = head;
ListNode pre = head;
while (null != fast && null != fast.next){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
return mergeTwoSortList(mergeSortList(head), mergeSortList(slow));
}
private static ListNode mergeTwoSortList(ListNode head1, ListNode head2){
if (null == head1){
return head2;
}
if (null == head2){
return head1;
}
ListNode head = new ListNode(-1);
ListNode cur = head;
ListNode cur1 = head1;
ListNode cur2 = head2;
while (null != cur1 && null != cur2){
if (cur2.val < cur1.val){
cur.next = cur2;
cur2 = cur2.next;
}else {
cur.next = cur1;
cur1 = cur1.next;
}
cur = cur.next;
}
if (null != cur1){
cur.next = cur1;
}
if (null != cur2){
cur.next = cur2;
}
return head.next;
}
排序前:6 2 8 4 9 5 1 3 7
排序后:1 2 3 4 5 6 7 8 9