一、题目
力扣原题:https://leetcode-cn.com/problems/sort-list/
二、归并排序
/**
* 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 (null == head) {
return null;
}
return split(head);
}
private ListNode split(ListNode node) {
if (null == node || null == node.next) {
return node;
}
// 双指针,标记链表中点
ListNode slow = node;
ListNode fast = node.next;
while (null != fast && null != fast.next) {
slow = slow.next;
fast = fast.next.next;
}
// 链表分割
ListNode pre = node;
ListNode post = slow.next;