-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortList.java
More file actions
52 lines (46 loc) · 1.22 KB
/
SortList.java
File metadata and controls
52 lines (46 loc) · 1.22 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
package t148;
public class SortList {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public ListNode merge(ListNode le,ListNode re){
ListNode root = new ListNode(-1);
ListNode cu = root;
while(le!=null&&re!=null){
if(le.val<re.val){
root.next = le;
root = root.next;
le = le.next;
}else{
root.next = re;
root = root.next;
re = re.next;
}
}
if(le!=null){
root.next = le;
}
if(re!=null){
root.next = re;
}
return cu.next;
}
public ListNode sortList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode pred,slow,fast;
pred = slow = fast = head;
while(fast!=null&&fast.next!=null){
pred = slow;
slow = slow.next;
fast = fast.next.next;
}
pred.next = null;
return merge(sortList(head),sortList(slow));
}
}