Sort a linked list in O(n log n) time using constant space complexity.
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode findMid(ListNode head) { ListNode pSlow = head; ListNode pFast = head; while (pFast.next!=null && pFast.next.next !=null) { pSlow = pSlow.next; pFast = pFast.next.next; } return pSlow; } public ListNode sortList(ListNode head) { if (head==null||head.next==null){ return head; } ListNode pMid = findMid(head); ListNode pMidRight = pMid.next; pMid.next = null; return merge(sortList(head),sortList(pMidRight)); } public ListNode merge(ListNode list1, ListNode list2) { if (list1==null || list2==null){ return list1==null ?list2 : list1; } ListNode result; ListNode p1 = list1; ListNode p2 = list2; //初始化头部 if (p1.val < p2.val) { result = p1; p1 = p1.next; } else { result = p2; p2 = p2.next; } ListNode p = result; //合并 while (p1!=null && p2!=null) { if (p2.val < p1.val) { p.next = p2; p2 = p2.next; p = p.next; } else { p.next = p1; p1 = p1.next; p = p.next; } } //补齐 while (p1!=null) { p.next = p1; p1 = p1.next; p = p.next; } while (p2!=null) { p.next = p2; p2 = p2.next; p = p.next; } return result; } }