0%

LeetCode-147

题目

Snipaste_2020-11-20_10-40-26.png

结果

Snipaste_2020-11-20_10-40-21.png

代码

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
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode ans = new ListNode(0);
ListNode p = head;
while (p != null) {
insert(ans, new ListNode(p.val));
p = p.next;
}
return ans.next;
}

private void insert(ListNode list, ListNode node) {
if (list.next == null) {
list.next = node;
return;
}

ListNode pre = list;
ListNode p = list.next;
while (p != null) {
if (node.val < p.val) {
pre.next = node;
node.next = p;
return;
}
pre = pre.next;
p = p.next;
}
pre.next = node;
}
}

复杂度

时间复杂度:O(n²)

空间复杂度:O(n)