单链表插入排序

来源:互联网 发布:《大数据时代》好句 编辑:程序博客网 时间:2024/06/05 20:11

public static Node Insertsort(Node head){

if (head==null||head.next==null) return head;
Node pre=new Node(-1);
pre.next=head;
Node nhead=pre;
Node p=head;
Node q=head.next;
while (q!=null){
if (q.val>=p.val){//p指向已排序的最后
p.next=q;
p=q;
q=q.next;
}else {
pre=nhead;         //pre指向已排序第一个元素的前一个
while (pre.next.val<q.val){
pre=pre.next;
}
p.next=q.next;//摘下q

q.next= pre.next;//q插到pre.next和pre之间
pre.next=q; //

q=p.next; //q指向p.next
}


}

return nhead.next;

}

原创粉丝点击