原题链接
解题思路
总体的思路是基于归并排序。
首先用快慢指针将链表分为两个部分,递归将两个部分进行归并排序。
归并排序主要和数组排序差不多,因为链表有指针相连,所以不用开辟另外的数据结构去存储(数组需要开辟一个数组去存储排序后的顺序)
解题代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
return mergeSort(head,null);
}
public ListNode mergeSort(ListNode begin,ListNode end) {
if (begin == end) {
if (begin != null) begin.next = null;
return begin;
}
ListNode slow = begin,fast = begin.next;
while(fast != end && fast.next != end) {
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
ListNode left = mergeSort(begin,slow);
ListNode right = mergeSort(fast,end);
begin = new ListNode(Integer.MAX_VALUE);
ListNode cur = begin;
while(left != null && right != null) {
if(left.val > right.val) {
cur.next = right;
right = right.next;
} else {
cur.next = left;
left = left.next;
}
cur = cur.next;
cur.next = null;
}
cur.next = left != null ? left:right;
return begin.next;
}
}