Insertion sort
[code]
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null || head.next==null)return head;
ListNode d=new ListNode(0);
d.next=head;
ListNode p=head.next, tail=head;
while(p!=null)
{
ListNode prev=d;
while(prev!=tail && prev.next.val<p.val)
{
prev=prev.next;
}
if(prev==tail)
{
tail.next=p;
p=p.next;
tail=tail.next;
}
else
{
ListNode next=p.next;
p.next=prev.next;
prev.next=p;
p=next;
}
}
tail.next=null;
return d.next;
}
}
merge sort
[code]
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null)return head;
ListNode mid=getMid(head);
ListNode left=head, right=mid.next;
mid.next=null;
left=sortList(left);
right=sortList(right);
return merge(left, right);
}
ListNode getMid(ListNode head)
{
ListNode p=head, q=head.next;
while(q!=null && q.next!=null)
{
p=p.next;q=q.next.next;
}
return p;
}
ListNode merge(ListNode p1, ListNode p2)
{
if(p1==null)return p2;
if(p2==null)return p1;
ListNode d=new ListNode(0), curr=d;
while(p1!=null && p2!=null)
{
if(p1.val<p2.val)
{
curr.next=p1;
curr=p1;
p1=p1.next;
}
else
{
curr.next=p2;
curr=p2;
p2=p2.next;
}
}
if(p1==null)curr.next=p2;
else curr.next=p1;
return d.next;
}
}
quick sort
[code]
OJ 在一个只包含1,2,3的very long list上超时。猜测是因为partition很不均匀,最坏情况是O(n^2)
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null)return head;
ListNode left=new ListNode(0), right=new ListNode(0), p=head.next, d1=left, d2= right;
while(p!=null){
if(p.val<head.val)
{
left.next=p;
left=p;
p=p.next;
}
else
{
right.next=p;
right=p;
p=p.next;
}
}
left.next=head;
head.next=null;
right.next=null;
left=sortList(d1.next);
right=sortList(d2.next);
ListNode dummy=new ListNode(0);
dummy.next=left;
p=dummy;
while(p.next!=null)p=p.next;
p.next=right;
return left;
}
}