Sort a linked list in O(n log n) time using constant space complexity.
public class SortList {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
/**
* 使用 LL ptr 快速排序
* @param head
* @return
*/
public ListNode sortList(ListNode head, ListNode end) {
if (head == null) {
return null;
}
ListNode comNode = head;
ListNode lessNode = head;
if (head.next == end) {
return head;
}
ListNode pNode = head.next;
while (pNode != end) {
if (pNode.val < comNode.val) {
swap(pNode, lessNode.next);
lessNode = lessNode.next;
}
pNode = pNode.next;
}
swap(lessNode, comNode);
sortList(head, lessNode);
sortList(lessNode.next, end);
return head;
}
private void swap (ListNode node1, ListNode node2) {
int temp = node1.val;
node1.val = node2.val;
node2.val = temp;
}
}