归并排序
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next==null) return head;
head = MergeSort(head);
return head;
}
public ListNode Merge(ListNode a, ListNode b) {
if(a == null && b == null) return null;
ListNode temp = new ListNode(0);
ListNode p = temp;
while(a!=null && b!=null) {
if (a.val < b.val) {
p.next = a;
p = p.next;
a = a.next;
} else {
p.next = b;
p = p.next;
b = b.next;
}
}
if (a!=null) p.next = a;
if (b!=null) p.next = b;
return temp.next;
}
public ListNode MergeSort(ListNode head) {
if (head == null || head.next==null) return head;
ListNode pSlow = head;
ListNode pFast = head.next;
while(pFast.next!=null && pFast.next.next!=null){
pSlow = pSlow.next;
pFast = pFast.next.next;
}
pFast = MergeSort(pSlow.next);
pSlow.next = null;
pSlow = MergeSort(head);
return Merge(pSlow, pFast);
}
}
快速排序
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next==null) return head;
QuickSort(head, null);
return head;
}
public void QuickSort(ListNode start, ListNode end) {
if (start == end) return;
ListNode a = start, b = start.next;
while(b!=end) {
if (b.val < start.val) {
a = a.next;
exch(a,b);
}
b = b.next;
}
exch(a, start);
QuickSort(start, a);
QuickSort(a.next, end);
}
private void exch(ListNode a, ListNode b) {
int temp = a.val;
a.val = b.val;
b.val = temp;
}
}