-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSortList.java
More file actions
55 lines (52 loc) · 1.19 KB
/
SortList.java
File metadata and controls
55 lines (52 loc) · 1.19 KB
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;
/**
* 148. Sort List
* Sort a linked list in O(n log n) time using constant space complexity.
*
* Example 1:
*
* Input: 4->2->1->3
* Output: 1->2->3->4
* Example 2:
*
* Input: -1->5->3->4->0
* Output: -1->0->3->4->5
*
*
*/
public class SortList {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode h = new ListNode();
h.next = head;
quikSort(h, null);
return h.next;
}
public void quikSort(ListNode head, ListNode tail)
{
if (head.next == tail || head.next.next == tail)
{
return;
}
ListNode compare = head.next;
ListNode idx = head.next;
while(idx.next != tail)
{
ListNode cur = idx.next;
if (cur.val < compare.val)
{
idx.next = idx.next.next;
cur.next = head.next;
head.next = cur;
continue;
}
idx = idx.next;
}
quikSort(head, compare);
quikSort(compare, tail);
}
public class ListNode {
public int val;
public ListNode next;
}
}