//链结点 public class Link { public long dData; public Link next; public Link(long dd) { dData=dd; } public void displayLink() { System.out.print(dData+" "); } }
public class SortedList { private Link first; public SortedList(Link[] linkArr) { first=null; for(int j=0;j<linkArr.length;j++) { insert(linkArr[j]); } } public void insert(Link k) { Link previous=null;//记录插入点的左节点 Link current=first;//记录插入点的右节点 while(current!=null&&k.dData>current.dData) { previous=current; current=current.next; } if(previous==null) first=k; else previous.next=k; k.next=current; } //从first端删除 public Link remove() { Link temp=first; first=first.next; return temp; } //遍历 public void display() { System.out.println("List(Fist-->last):"); Link current=first; while(current!=null) { current.displayLink(); current=current.next; } System.out.println(); } }
public class Test { public static void main(String[] args) { int size=10; Link[] linkArray=new Link[size]; for(int j=0;j<size;j++) { int n=(int)(java.lang.Math.random()*99); Link newLink=new Link(n); linkArray[j]=newLink; } System.out.print("unsorted array:"); for(int j=0;j<size;j++) { System.out.print(linkArray[j].dData+" "); } System.out.println(); SortedList theSortedList=new SortedList(linkArray); theSortedList.display(); System.out.println("sorted Array:"); for(int j=0;j<size;j++) { linkArray[j]=theSortedList.remove(); } for(int j=0;j<size;j++) { System.out.print(linkArray[j].dData+" "); } } }