-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path148.java
More file actions
87 lines (83 loc) · 2.6 KB
/
148.java
File metadata and controls
87 lines (83 loc) · 2.6 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
__________________________________________________________________________________________________
sample 1 ms submission
/**
* 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;
// quicksort
ListNode pivot = head;
ListNode node = head.next;
ListNode sHead = new ListNode(Integer.MIN_VALUE);
ListNode lHead = new ListNode(Integer.MIN_VALUE);
ListNode sCurrent = sHead, lCurrent = lHead, eCurrent = head;
while (node != null) {
if (node.val == pivot.val) {
eCurrent.next = node;
eCurrent = eCurrent.next;
} else if (node.val <= pivot.val) {
sCurrent.next = node;
sCurrent = sCurrent.next;
} else {
lCurrent.next = node;
lCurrent = lCurrent.next;
}
node = node.next;
}
sCurrent.next = lCurrent.next = null;
sHead.next = sortList(sHead.next);
lCurrent = sortList(lHead.next);
sCurrent = sHead;
while (sCurrent.next != null) {
sCurrent = sCurrent.next;
}
sCurrent.next = head;
eCurrent.next = lCurrent;
return sHead.next;
}
}
__________________________________________________________________________________________________
sample 37564 kb submission
/**
* 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)
return null;
if (head.next == null)
return head;
List<Integer> list = new ArrayList<>();
while (head.next != null) {
list.add(head.val);
head = head.next;
}
list.add(head.val);
Collections.sort(list);
return toLinkedList(list);
}
private static ListNode toLinkedList(List<Integer> list) {
if (list == null || list.isEmpty())
return null;
ListNode head = new ListNode(list.get(0));
ListNode tail = head;
for (int i=1; i<list.size(); i++) {
tail.next = new ListNode(list.get(i));
tail = tail.next;
}
return head;
}
}
__________________________________________________________________________________________________