-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148-sortList.java
More file actions
56 lines (56 loc) · 1.42 KB
/
148-sortList.java
File metadata and controls
56 lines (56 loc) · 1.42 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution_148 {
// 归并排序
public ListNode sortList(ListNode head) {
if(head == null) return null;
return mergeSort(head);
}
public ListNode mergeSort(ListNode head) {
if(head.next == null) return head;
ListNode fast = head, slow = head, pre=null;
// 链表找中点的方式
while(fast!=null&&fast.next!=null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
pre.next = null;
ListNode l = mergeSort(head);
ListNode r = mergeSort(slow);
return merge(l, r);
}
// 合并,注意多出来的那段
public ListNode merge(ListNode l, ListNode r) {
ListNode newHead = new ListNode(0);
ListNode cur = newHead;
while(l != null && r != null) {
if(l.val <= r.val) {
cur.next = l;
l = l.next;
} else {
cur.next = r;
r = r.next;
}
cur = cur.next;
}
if(l!=null) {
cur.next = l;
}
if(r!=null){
cur.next = r;
}
return newHead.next;
}
}