Sort List

Sort a linked list in O(n log n) time using constant space complexity.

思想: divede and conquer,利用主定理公式,复杂度为O(nlogn).先用slow和fast指针分解两个链表,第一个链表的尾部节点为null。然后用merge算法合并。

  1. public ListNode merge(ListNode f1,ListNode f2) {
  2. ListNode dummy = new ListNode(-1);
  3. dummy.next = f1;
  4. ListNode tmp=dummy;
  5. while(f1!=null && f2!=null) {
  6. if(f1.val > f2.val) {
  7. ListNode p=f2;
  8. f2=f2.next;
  9. tmp.next=p;
  10. p.next=f1;
  11. } else {
  12. f1=f1.next;
  13. }
  14. tmp=tmp.next;
  15. }
  16. if(f1==null) tmp.next=f2;
  17. return dummy.next;
  18. }
  19. public ListNode sortList(ListNode head) {
  20. if(head==null || head.next==null) return head;
  21. ListNode slow=head;
  22. ListNode fast=head;
  23. while(fast.next!=null) {
  24. fast=fast.next.next;
  25. if(fast==null) break;
  26. slow=slow.next;
  27. }
  28. ListNode second = slow.next;
  29. slow.next=null;
  30. ListNode f1 = sortList(head);
  31. ListNode f2 = sortList(second);
  32. return merge(f1,f2);
  33. }
posted @ 2014-07-28 20:50  purejade  阅读(82)  评论(0编辑  收藏  举报