-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
55 lines (47 loc) · 1.51 KB
/
Solution.java
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
49
50
51
52
53
54
55
package leetcode.algo.list.leet_zh_148;
import leetcode.algo.list.base.ListNode;
public class Solution {
/*
*
* 148. 排序链表
*
* 16 / 16 个通过测试用例
* 执行用时:922 ms
*
* 执行用时 : 922 ms, 在Sort List的Java提交中击败了6.22% 的用户
* 内存消耗 : 44.3 MB, 在Sort List的Java提交中击败了60.95% 的用户
* */
public ListNode sortList(ListNode head) {
if (head == null)
return null;
return partition(head, null);
}
private ListNode partition(ListNode start, ListNode end) {
if (start == null) return null;
if (start == end) return start;
ListNode des = start;
ListNode head = des;
ListNode pre = start;
ListNode cur = start.next;
while (cur != end && cur != null) {
if (cur.val <= des.val) {
pre.next = cur.next; // del cur
cur.next = head; // insert before head
head = cur; // head
cur = pre.next; // next cur
} else {
pre = pre.next;
cur = cur.next;
}
}
des.next = partition(des.next, cur);
head = partition(head, des);
return head;
}
public static void main(String[] args) {
Solution ss = new Solution();
int[] arr = {4, 2, 1, 3, 1, 2, 2, 3, 1, 1, 10, 2, 9, 5, 7};
ListNode head = new ListNode(arr);
System.out.println(ss.sortList(head));
}
}