题目:
Sort a linked list in O(n log n) time using constant space complexity.
分析:
选择用归并排序来解决。但是找中点的时候需要注意对于 1 --> 2 --> null 的情况,我们需要mid为1,才能把1和2分开,找中点的时候让fast先走一步即可。
1. 如果链表为空或只有一个节点,直接返回该节点,否则,找中点。
2. 左右半边递归的排序
3. 合并排好序的左右两边
Java代码实现:
/**
* 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) {
if(head==null || head.next==null)
return head;
ListNode mid = findmid(head);
ListNode right = mid.next;
mid.next = null;
ListNode left = head;
left = sortList(left);
right = sortList(right);
return merge(left, right);
}
private ListNode findmid(ListNode head)
{
ListNode fast = head.next;
ListNode slow = head;
while(fast!=null && fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
private ListNode merge(ListNode l1, ListNode l2)
{
ListNode dummy = new ListNode(0);
ListNode node = dummy;
while(l1!=null && l2!=null)
{
if(l1.val<=l2.val)
{
node.next = l1;
l1 = l1.next;
}
else
{
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
if(l1!=null)
node.next = l1;
if(l2!=null)
node.next = l2;
return dummy.next;
}
}