Sort a linked list in O(n log n) time using constant space complexity.
Input: 4->2->1->3
Output: 1->2->3->4
Input: -1->5->3->4->0
Output: -1->0->3->4->5
这道题是对列表进行排序,要求时间复杂度是nlogn,我用的是归并排序,和数组归并排序不同的是找到中点,在列表中通过快慢指针找中点,当快指针到达终点时慢指针到达中点,然后就是一般的归并排序思想
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
//递归出口
if (head == null || head.next == null) {
return head;
}
//找到中点
ListNode middle = findMiddle(head);
//排序右面
ListNode right = sortList(middle.next);
//排序左面
middle.next = null;
ListNode left = sortList(head);
//左右归并
return merge(left, right);
}
//快慢指针找列表中点
private ListNode findMiddle(ListNode node) {
ListNode slow = node, fast = node.next;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
//列表merge操作
private ListNode merge(ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while(head1 != null && head2 != null) {
if (head1.val < head2.val) {
tail.next = head1;
head1 = head1.next;
} else {
tail.next = head2;
head2 = head2.next;
}
tail = tail.next;
}
if (head1 != null) {
tail.next = head1;
} else {
tail.next = head2;
}
return dummy.next;
}
}