题目描述
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
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 start = head;
ListNode mid = getMid(head);
ListNode end = mid.next;
mid.next = null;
return merge(sortList(start),sortList(end));
}
public ListNode merge(ListNode node1, ListNode node2){
if(node1 == null) {
return node2;
}
if(node2 == null){
return node1;
}
ListNode min = new ListNode(-1);
ListNode cur = min;
while(node1!=null && node2!=null){
if(node1.val < node2.val){
cur.next = node1;
node1 = node1.next;
}else{
cur.next = node2;
node2 = node2.next;
}
cur = cur.next;
}
if(node1 != null){
cur.next = node1;
}
if(node2 != null ){
cur.next = node2;
}
return min.next;
}
// 采用快慢指针获取链表的中间节点
public ListNode getMid(ListNode node){
if(node == null || node.next == null){
return node;
}
ListNode slow = node;
ListNode fast = node;
while(fast.next != null && fast.next.next!= null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}