leetcode-sort-list

题目大意

  https://leetcode.com/problems/sort-list/

  单链表排序,要求时间复杂度O(n*logn),空间复杂度:O(1)

题目分析

  先利用快慢指针找到链表中点,然后每段递归调用,最后merge两个链表

代码

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
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) { // 这里注意head.next == null的判断
return head;
}
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
while (fast != null) {
fast = fast.next;
if (fast != null) {
fast = fast.next;
}
pre = slow;
slow = slow.next;
}
ListNode p1 = sortList(slow);
pre.next = null;
ListNode p2 = sortList(head);
// merge two sorted linked list
ListNode newHead = new ListNode(-1);
ListNode cur = newHead;
while (p1 != null || p2 != null) {
if (p1 == null) {
cur.next = p2;
break;
}
if (p2 == null) {
cur.next = p1;
break;
}
if (p1.val < p2.val) {
cur.next = p1;
p1 = p1.next;
} else {
cur.next = p2;
p2 = p2.next;
}
cur = cur.next;
}
return newHead.next;
}
}