排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序
思路:
(1) 寻找中间节点,分成两个子链表
(2) 对两个子链表进行归并排序
(3) 合并有序链表
代码:
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode middle = middleNode(head);
ListNode rightHead = middle.next;
middle.next = null;
ListNode left = sortList(head);
ListNode right = sortList(rightHead);
return merge(left, right);
}
//寻找中间节点
private ListNode middleNode(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;
}
return slow;
}
//合并两个有序链表
private ListNode merge(ListNode list1, ListNode list2){
ListNode head = new ListNode(-1);
ListNode node = head;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
node.next = list1;
list1 = list1.next;
}else{
node.next = list2;
list2 = list2.next;
}
node = node.next;
}
if(list1 != null) node.next = list1;
if(list2 != null) node.next = list2;
return head.next;
}
}