针对链表的排序:通过快慢指针找到中点,使用归并排序

    1. class Solution {
    2. public ListNode sortList(ListNode head) {
    3. return mergeSort(head);
    4. }
    5. public ListNode mergeSort(ListNode head) {
    6. if(head == null || head.next == null ) return head;
    7. ListNode fast = head;
    8. ListNode dummy = new ListNode();
    9. dummy.next = head;
    10. ListNode slow = dummy;
    11. while(fast != null && fast.next != null){
    12. slow = slow.next;
    13. fast = fast.next.next;
    14. }
    15. ListNode newHead = slow.next;
    16. slow.next = null;
    17. ListNode l1 = mergeSort(head);
    18. ListNode l2 = mergeSort(newHead);
    19. return merge(l1,l2);
    20. }
    21. ListNode merge(ListNode l1,ListNode l2){
    22. ListNode dummy = new ListNode();
    23. ListNode cur = null;
    24. cur = dummy;
    25. while(l1 != null && l2 != null){
    26. if(l1.val > l2.val){
    27. cur.next = l2;
    28. l2 = l2.next;
    29. }else{
    30. cur.next = l1;
    31. l1 = l1.next;
    32. }
    33. cur = cur.next;
    34. }
    35. cur.next = l1 == null ? l2 : l1;
    36. return dummy.next;
    37. }
    38. }