题目链接
思路
- 这个题目可以用归并排序来做~
- 首先需要一个split函数,用于分隔链表(相当于数组归并排序的取mid)
- 然后需要一个merge函数,用于把两个链表归并,并返回归并后的头指针~
- 最后递归调用即可~ 注意递归的条件
class Solution {
private ListNode split(ListNode head) {
ListNode slow = head, fast = head.next.next;
while (null != fast) {
slow = slow.next;
fast = fast.next;
if (null != fast)
fast = fast.next;
}
fast = slow.next;
slow.next = null;
return fast;
}
private ListNode merge(ListNode first, ListNode second) {
ListNode dummy = new ListNode(0), head = dummy;
while (null != first && null != second) {
if (first.val < second.val) {
head.next = first;
first = first.next;
} else {
head.next = second;
second = second.next;
}
head.next.next = null;
head = head.next;
}
head.next = null == first ? second : first;
return dummy.next;
}
public ListNode sortList(ListNode head) {
if (null == head || null == head.next)
return head;
ListNode mid = split(head);
ListNode left = sortList(head), right = sortList(mid);
return merge(left,right);
}
}