题目如下:
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
解答如下:
这题主要是要求空间复杂度要低,然后时间复杂度是nlogn..所以归并排序比较合适。然后设置快慢指针用来找到中间节点,然后划分再归并。
代码:
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode fast = head;
ListNode slow = head;
//快慢指针得到中间点
while(fast.next!=null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
}
//将链表拆成两半
fast = slow.next;
slow.next = null;
//左右两半分别排序
ListNode p1 = sortList(head);
ListNode p2 = sortList(fast);
//合并
return merge(p1, p2);
}
public ListNode merge(ListNode l1, ListNode l2) {
if(l1==null) {
return l2;
} else if (l2==null) {
return l1;
} else if (l1==null && l2==null) {
return null;
}
ListNode dummy=new ListNode(0);
ListNode p = dummy;
while(l1!=null && l2!=null) {
if(l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l1!=null) {
p.next = l1;
} else if(l2!=null){
p.next = l2;
}
return dummy.next;
}
}