# 排序列表

``````输入：head = [4,2,1,3]

``````输入：head = [-1,5,3,4,0]

``````输入：head = []

• 链表中节点的数目在范围 [0, 5 * 104] 内
• -105 <= Node.val <= 105

• 遍历链表获取所有节点的值
• 将所有节点值进行升序排列
• 利用排序后的结果重构新的链表

``````/**
* 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; }
* }
*/
class Solution {

List<Integer> list = new ArrayList<>();
while(cur != null){
cur = cur.next;
}

list.sort((o1, o2) -> o1-o2);
ListNode dummy = new ListNode();
cur = dummy;
for(Integer e : list){
cur.next = new ListNode(e);
cur = cur.next;
}

return dummy.next;
}
}

• 采用快慢指针来寻找链表中点

• 将中点左右的两个有序子链表合并

• 设置好递归出口，即：

• h e a d = = n u l l head == null head==null，表示链表为空
• 或者 h e a d . n e x t = = t a i l head.next == tail head.next==tail，表示只包含一个节点

``````/**
* 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; }
* }
*/
class Solution {

}

public ListNode sortList(ListNode head, ListNode tail){
// 递归出口
}

// 平均断开链表
// 快慢指针寻找中点
while (fast != tail) {
slow = slow.next;
fast = fast.next;
if (fast != tail) {
fast = fast.next;
}
}

ListNode right = sortList(slow, tail);
ListNode mer = mergeList(left, right);
return mer;
}

public ListNode mergeList(ListNode left, ListNode right){
ListNode dummy = new ListNode();
ListNode cur = dummy;
while(left != null && right != null){
if(left.val <= right.val){
cur.next = left;
left = left.next;
} else {
cur.next = right;
right = right.next;
}
cur = cur.next;
}

if(left != null){
cur.next = left;
} else if(right != null){
cur.next = right;
}

return dummy.next;
}
}