Sort a linked list in O(n log n) time using constant space complexity.
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode SortList(ListNode head) {
if(head == null || head.next == null){
return head;//注意这里是要求返回ListNode类型的
}
//1. cut the list
var pre = head;
var slow = head;
var fast = head;
while(fast != null && fast.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;//切断
//2. sort each helf
var listNode1 = SortList(head);
var listNode2 = SortList(slow);
//3. merge
return MergeSort(listNode1, listNode2);
}
private ListNode MergeSort(ListNode firstHead, ListNode secondHead){
var newListNode = new ListNode(0);
var tempNode = newListNode;
while(firstHead != null && secondHead != null){
if(firstHead.val < secondHead.val){
tempNode.next = firstHead;
firstHead = firstHead.next;
}else{
tempNode.next = secondHead;
secondHead = secondHead.next;
}
tempNode = tempNode.next;
}
if(firstHead != null){
tempNode.next = firstHead;
}
if(secondHead != null){
tempNode.next = secondHead;
}
return newListNode.next;
}
}