1、Link结构
public class Link {
public long dData;
public Link next;
public Link(long dd){
dData = dd;
}
public void displayLink(){
System.out.print(dData + " ");
}
}
2、排序类
public class SortedList {
private Link first;
public SortedList(){
first = null;
}
public boolean isEmpty(){
return (first == null);
}
public SortedList(Link[] linkArr){
first = null;
for(int i = 0;i < linkArr.length; i ++){
insert(linkArr[i]);
}
}
/**
* 插入
* @param k
*/
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;
}
/**
* 插入
* @param key
*/
public void insert(long key){
Link newLink = new Link(key);//创建新的实体
Link previous = null;//默认链表前一个为null
Link current = first;//默认链表第一个为当前对象
/**
* 核心
* 遍历链表,寻找当前值在那两个值之间。
*/
while(current != null && key>current.dData){//当前对象不为空,且值大于当前对象
previous = current;//以前值等于当前值
current = current.next;//当前值等于当前值的下一个值
}
if(previous == null){//如果以前的值为空
first = newLink;//第一个值为新值
}else{
previous.next = newLink;//否者以前值的下一个值为新值
}
newLink.next = current;//新值的下一个值为当前值
}
public Link remove(){
Link temp = first;
first = first.next;
return temp;
}
public void displayList(){
System.out.print("List (first --> last: ");
Link current = first;
while(current != null){
current.displayLink();
current= current.next;
}
System.out.println(" ");
}
}
3、测试类
public class SortedListApp {
/**
* 有序链表
*/
@Test
public void test1(){
SortedList theSortedList = new SortedList();
theSortedList.insert(20);
theSortedList.insert(40);
theSortedList.displayList();
theSortedList.insert(10);
theSortedList.insert(30);
theSortedList.insert(50);
theSortedList.displayList();
theSortedList.remove();
theSortedList.displayList();
}
/**
* 表插入排序
*/
@Test
public void test2(){
Link[] linkArray = new Link[10];
/**
* 随即数生成链表数组的数据
*/
for(int i = 0; i< linkArray.length; i ++){
int n = (int)(java.lang.Math.random()*99);
Link newLink = new Link(n);
linkArray[i] = newLink;
}
/**
* 输出未排序的
*/
System.out.print("Unsorted array: ");
for(int i = 0; i< linkArray.length; i ++){
System.out.print(linkArray[i].dData + " ");
}
System.out.println(" ");
/**
* 创建链表并插入,且排序
*/
SortedList theSortedList = new SortedList(linkArray);
/**
* 将排序后链表结果返回到数组中
*/
for(int i = 0; i< linkArray.length; i ++){
linkArray[i] = theSortedList.remove();
}
/**
* 展示排序后的列表
*/
System.out.print("Sorted Array : ");
for(int i = 0; i< linkArray.length; i ++){
System.out.print(linkArray[i].dData + " ");
}
System.out.println(" ");
}
}
4、运行结果
test1:
List (first --> last: 20 40
List (first --> last: 10 20 30 40 50
List (first --> last: 20 30 40 50
test2:
Unsorted array: 82 96 10 56 62 33 35 72 14 54
Sorted Array : 10 14 33 35 54 56 62 72 82 96
Reference:
[1] Robert Lalore(著) 计晓云,赵研,曾希,狄小菡(译), Java数据结构和算法(第二版),中国电力出版社,2004 :158-165