-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSolution148.java
34 lines (31 loc) · 920 Bytes
/
Solution148.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
package LinkedList_problem;
/**
* 排序链表:【merge sort + Floyd】
*/
public class Solution148 {
public ListNode sortList(ListNode head){
if (head==null||head.next==null) return head;
ListNode fast = head.next;
ListNode slow = head;
while (fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
ListNode curr = slow.next;
slow.next = null;
head = sortList(head);
curr = sortList(curr);
ListNode pre = new ListNode(0);
slow = pre;
while (head!=null&&curr!=null){
if (head.val<curr.val){
pre.next = head; pre = pre.next; head = head.next;
}
else{
pre.next = curr; pre = pre.next; curr = curr.next;
}
}
pre.next = head==null? curr:head;
return slow.next;
}
}