Sort a linked list in O(n log n) time using constant space complexity.
思想
歸并排序 n O(logn)
快慢指針找到單鏈表的中點
代碼
package linkList;
/**
* Sort a linked list in O(n log n) time using constant space complexity.
* Created by liqiushi on 2018/1/9.
*/
public class SortList {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
//使用快慢指針分割
ListNode slow = head;
ListNode fast = head;
ListNode prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
//鏈表截斷 head->prev->null允扇、slow->fast->null/slow-null
prev.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
return merge(l1, l2);
}
public ListNode merge(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode rptr = result;
ListNode pptr = l1;
ListNode qptr = l2;
//遍歷l1、l2
while (pptr != null && qptr != null) {
if (pptr.val <= qptr.val) {
rptr.next = pptr;
pptr = pptr.next;
} else {
rptr.next = qptr;
qptr = qptr.next;
}
rptr = rptr.next;
}
if (pptr != null) {
rptr.next = pptr;
} else {
rptr.next = qptr;
}
//若其中一個隊列遍歷完畢
return result.next;
}
}