//在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
//
// 示例 1:
//
// 输入: 4->2->1->3
//输出: 1->2->3->4
//
//
// 示例 2:
//
// 输入: -1->5->3->4->0
//输出: -1->0->3->4->5
// Related Topics 排序 链表
// 👍 645 👎 0
class Solution {
/**
* 二分法:时间复杂度 O(nlogn), 空间复杂度O(1)
* @param head
* @return
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 截断分为两部分链表
// 右部分节点头节点
ListNode rightHead = slow.next;
// 左部分头结点即为head
slow.next = null;
// 递归截断, 直至变为1个节点
ListNode left = sortList(head);
ListNode right = sortList(rightHead);
// 归并排序
ListNode node = new ListNode(-1);
ListNode resultHead = node;
while (left != null && right != null) {
if (left.val < right.val) {
node.next = left;
left = left.next;
node = node.next;
} else {
node.next = right;
node = node.next;
right = right.next;
}
}
node.next = left == null ? right : left;
return resultHead.next;
}
/**
* 时间复杂度: On, 空间复杂度On
* @param head
* @return
*/
public ListNode sortList2(ListNode head) {
if (head == null) {
return head;
}
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
ListNode node = new ListNode(-1);
ListNode pHead = node;
for (int i = 0; i < list.size(); i++) {
node.next = new ListNode(list.get(i));
node = node.next;
}
return pHead.next;
}
}