Sort a linked list in O(n log n) time using constant space complexity.
O(n lg n) constant space的常见sort方法有 merge sort, quick sort, heap sort。 quick sort 需要random choose 哨兵,Merge更加适合linked list。注意对半分的时候不要忘了将左半边的tail变为null。
public ListNode SortList(ListNode head) { if (head == null || head.next == null) return head; // step 1. cut the list to two halves ListNode prev = null, slow = head, fast = head; while (fast != null && fast.next != null) { prev = slow; slow = slow.next; fast = fast.next.next; } prev.next = null; // step 2. sort each half ListNode l1 = SortList(head); ListNode l2 = SortList(slow); // step 3. merge l1 and l2 return Merge(l1, l2); } private ListNode Merge(ListNode left, ListNode right ) { ListNode stand = new ListNode(0); ListNode l = stand; while( left!= null && right != null) { if(left.val < right.val) { l.next = left; left = left.next; } else { l.next = right; right = right.next; } l = l.next; } if (left != null) l.next = left; if (right != null) l.next = right; return stand.next; }
链表O(nlgn)排序
本文介绍了一种在O(n log n)时间内使用常数空间复杂度对链表进行排序的方法。主要讨论了归并排序算法在链表排序中的应用,并提供了具体的Java代码实现。
2224

被折叠的 条评论
为什么被折叠?



