题目:
Sort a linked list in O(n log n) time using constant space complexity.
思路:
考虑到要求用O(nlogn)的时间复杂度和constant space complexity来sort list,自然而然想到了merge sort方法。同时我们还已经做过了merge k sorted list和merge 2 sorted list。这样这个问题就比较容易了。
不过这道题要找linkedlist中点,那当然就要用最经典的faster和slower方法,faster速度是slower的两倍,当faster到链尾时,slower就是中点,slower的next是下一半的开始点。
解决了这些问题,题目就很容易解出了。
代码:
1 public class Solution { 2 public ListNode sortList(ListNode head) 3 { 4 if(head==null||head.next==null) return head; 5 6 ListNode fast = head; 7 ListNode slow = head; 8 ListNode firsthalf = head; 9 10 while(fast.next!=null&&fast.next.next!=null) 11 { 12 slow = slow.next; 13 fast = fast.next.next; 14 } 15 16 ListNode secondhalf = slow.next; 17 slow.next=null; 18 19 ListNode rightlist = null; 20 ListNode leftlist = null; 21 if(firsthalf!=secondhalf) 22 { 23 rightlist = sortList(secondhalf); 24 leftlist = sortList(firsthalf); 25 } 26 27 return mergeList(rightlist,leftlist); 28 29 } 30 31 public ListNode mergeList(ListNode rightlist, ListNode leftlist) 32 { 33 if(rightlist==null) 34 { 35 return leftlist; 36 } 37 38 if(leftlist==null) 39 { 40 return rightlist; 41 } 42 43 ListNode fakehead = new ListNode(0); 44 ListNode ptr = fakehead; 45 46 while(rightlist!=null&&leftlist!=null) 47 { 48 if(rightlist.val<leftlist.val) 49 { 50 ptr.next=rightlist; 51 ptr=ptr.next; 52 rightlist=rightlist.next; 53 } 54 else 55 { 56 ptr.next=leftlist; 57 ptr=ptr.next; 58 leftlist=leftlist.next; 59 60 } 61 } 62 63 if(rightlist!=null)ptr.next = rightlist; 64 if(leftlist!=null)ptr.next = leftlist; 65 return fakehead.next; 66 67 } 68 69 }
http://www.cnblogs.com/springfor/p/3869372.html