/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode sortList(ListNode head) {
// 2015-5-24 O(nlogn) 分治法 递归 类似归并排序
// exit condition
if (head == null || head.next == null) {
return head;
}
ListNode mid = findMid(head);
ListNode listB = sortList(mid.next);
mid.next = null;
ListNode listA = sortList(head);
// listB 不长于 listA
return mergeList(listA, listB);
}
private ListNode findMid(ListNode head) {
if (head == null) {
return head;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode mergeList(ListNode listA, ListNode listB) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (listA != null && listB != null) {
if (listA.val < listB.val) {
tail.next = listA;
listA = listA.next;
} else {
tail.next = listB;
listB = listB.next;
}
tail = tail.next;
}
if (listA != null) {
tail.next = listA;
}
if (listB != null) {
tail.next = listB;
}
return dummy.next;
}
}
[刷题]Sort List
最新推荐文章于 2022-03-21 23:57:40 发布