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;
}
}