05 August 2008
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
1
2
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
1
2
Input: -1->5->3->4->0
Output: -1->0->3->4->5
用 O(n log n) 的复杂度对链表中的元素进行排序。既然是_O_(n log n)复杂度的排序,那自然就是想到快排(复杂度平均)或者归并排序,这里用归并排序比较合适。根据Merge Sort的基本思想,就是找到中间结点,然后对左右两半部分分别进行归并排序,最后对排好序的两部分链表进行merge。通常Merge Sort是针对数组来看的,这里是链表,找到中间结点的办法是快慢指针;然后是合并两个有序链表,迭代或递归。最后返回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 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 = getMiddleOfList(head);
ListNode next = middle.next;
middle.next = null;//把链表断开分为左边(包括middle结点)和右边
return mergeTwoList(sortList(head), sortList(next));
}
//快慢指针找到中间结点
private ListNode getMiddleOfList(ListNode 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 mergeTwoList(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1), current = dummy;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
current.next = l1 == null ? l2 : l1;
return dummy.next;
}
}