归并排序
class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode fast=head,low=head;
while(fast.next!=null && fast.next.next!=null){
fast=fast.next.next;
low=low.next;
}
fast=low.next;
low.next=null;
ListNode res1=sortList(head);
ListNode res2=sortList(fast);
return Merge(res1,res2);
}
ListNode Merge(ListNode p1,ListNode p2){
ListNode p=new ListNode(0);
p.next=null;
ListNode t0=p;
while(p1!=null && p2!=null){
if(p1.val<p2.val){
ListNode temp=p1;
p1=p1.next;
t0.next=temp;
t0=t0.next;
t0.next=null;
}else{
ListNode temp=p2;
p2=p2.next;
t0.next=temp;
t0=t0.next;
t0.next=null;
}
}
t0.next=p1==null?p2:p1;
return p.next;
}
}
快速排序
class Solution {
public ListNode sortList(ListNode head) {
Qsort(head,null);
return head;
}
void Qsort(ListNode head,ListNode tail){
if(head==null || head.next==null || head==tail)
return;
ListNode cur=head.next;
ListNode pre=head;
int key=head.val;
while(cur!=tail){
if(cur.val<key){
pre=pre.next;
Swap(pre,cur);
}
cur=cur.next;
}
Swap(pre,head);
Qsort(head,pre);
Qsort(pre.next,tail);
}
public void Swap(ListNode node1,ListNode node2){
int val=node1.val;
node1.val=node2.val;
node2.val=val;
}
}
插入排序
选择排序