题目:
给定一个节点数为n的无序单链表,对其按升序排序。
数据范围:0<n≤100000。
要求:时间复杂度 O(nlogn)。
示例1
输入:{1,3,2,4,5}
返回值:{1,2,3,4,5}
示例2
输入:{-1,0,-2}
返回值:{-2,-1,0}
思路:分治法
将整个链表拆分到只剩一个节点,然后再复用合并两个有序链表的方法。
代码:
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
//1.边界治理
if(head == null || head.next == null){
return head;
}
//2.定义一个左指针,右指针
ListNode left = head;
ListNode mid = head.next;
ListNode right = head.next.next;
while(right != null && right.next != null){
left = left.next;
mid = mid.next;
right = right.next.next;
}
ListNode rightpart = left.next;
//left已经在中间
//变成两个链表
left.next = null;
return Merge(sortInList(head), sortInList(rightpart));
}
//合并两个有序链表
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode dummy = new ListNode(-1);
ListNode res = dummy;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
res.next = list1;
list1 = list1.next;
res = res.next;
}else{
res.next = list2;
list2 = list2.next;
res = res.next;
}
}
if(list1 != null){
res.next = list1;
}
if(list2 != null){
res.next = list2;
}
return dummy.next;
}
}