public class LinkSort_Insert {
/**
* 题目描述: 给定一个单链表,要求对其进行排序,不得使用辅助数组或更改节点中的数值;
* 思路:插入排序在对顺序数组进行排序时需要涉及大量移动数组元素,但对于链表其插入过程较为简单,但时间复杂度依然为O(N);
* @param args
*/
public static class Node{
public int data;
public Node next;
public Node(int data){
this.data=data;
this.next=null;
}
}
public Node head;
public LinkSort_Insert(int[] list){
head=new Node(list[0]);
Node now=head;
for(int i=1;i<list.length;i++){
Node one=new Node(list[i]);
now.next=one;
now=one;
}
}
public void InsertSort(){
if(head==null){
return;
}
Node now=head.next;
Node next;
Node start;
Node end=head;
while(now!=null){
next=now.next;
start=head;
int flag=0;
while(!start.equals(now)){
if(now.data<start.data){
end.next=now.next;
now.next=start;
head=now;
flag=1;
break;
}else if(now.data>=start.data&&now.data<start.next.data){
end.next=next;
now.next=start.next;
start.next=now;
flag=1;
break;
}else{
start=start.next;
}
}
if(flag==0){
end=now;
}
now=next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list={10,9,9,88,8,12,7,23,6,45,5,4,99,3,111,2,190,1};
LinkSort_Insert lsi=new LinkSort_Insert(list);
lsi.InsertSort();
Node head=lsi.head;
while(head!=null){
System.out.println(head.data);
head=head.next;
}
}
}
链表之排序
最新推荐文章于 2024-04-11 21:39:22 发布