题目描述
Sort a linked list in O(n log n) time using constant space complexity.
由于限制了时间复杂度,所以选择使用归并排序
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next==null)
return head;
ListNode slow = head;
ListNode fast = head;
while(fast.next!=null && fast.next.next!=null){
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
slow = sortList(head);
fast = sortList(fast);
head = mergeSort(slow,fast);
return head;
}
public ListNode mergeSort(ListNode head1,ListNode head2){
if(head1==null)
return head2;
if(head2 ==null)
return head1;
ListNode head=null;
if(head1.val>head2.val){
head = head2;
head.next = mergeSort(head1,head2.next);
}else{
head = head1;
head.next = mergeSort(head1.next,head2);
}
return head;
}
}