有序链表:存储有序数据的链表结构为有序链表.
有了以前链表的基础.写起来就很简单了.无非是从first循环链结点,一直找到一个大于当前链结点关键字的那个链结点.将追加的
这个链结点插到前面即可.需要注意的就是插入在头部和尾部的特殊处理.
下面写了个用有序链表做排序:
package
com.dbstructor.oop5;
class
Link {
public
int
dData;
public
Link next;
public
Link(
int
dd){
dData
=
dd;
}
public
void
displayLink() {
System.out.print(dData
+
“
“
);
}
}
class
SortedList {
public
Link first;
public
SortedList(Link[] arrLink) {
first
=
null
;
for
(
int
i
=
0
; i
<
arrLink.length; i
++
){
insertFirst(arrLink[i].dData);
}
}
public
void
insertFirst(
int
dd){
Link newLink
=
new
Link(dd);
Link privious
=
null
;
//
这个标志很重要用来判定是否是表头
Link current
=
first;
//
如果current在表头或者表尾并且找到一个大于比较数据的链结点就退出循环
while
(current
!=
null
&&
current.dData
<
dd ){
privious
=
current;
current
=
current.next;
}
//
如果在表头就让首链结点直接指向
if
(privious
==
null
) {
first
=
newLink;
}
//
否则在表尾让最后一个结点指向他
else
{
privious.next
=
newLink;
}
//
不管如何这个结点的next指向最后
newLink.next
=
current;
}
public
Link remove(){
Link temp
=
first;
first
=
first.next;
return
first;
}
public
void
displayList() {
Link current
=
first;
while
(current
!=
null
){
current.displayLink();
current
=
current.next;
}
System.out.println();
}
}
public
class
SortedListApp {
public
static
void
main(String[] args) {
int
size
=
10
;
Link[] arrLink
=
new
Link[
10
];
for
(
int
i
=
0
; i
<
arrLink.length; i
++
){
Link newLink
=
new
Link((
int
)(Math.random()
*
99
));
arrLink[i]
=
newLink;
}
System.out.print(
“
unSorted:
“
);
for
(
int
i
=
0
; i
<
arrLink.length; i
++
){
System.out.print(arrLink[i].dData
+
“
“
);
}
System.out.println();
System.out.print(
“
Sorted:
“
);
SortedList theList
=
new
SortedList(arrLink);
theList.displayList();
}
}
运行结果为:
unSorted:
36
40
6
19
12
31
27
40
56
14
Sorted:
6
12
14
19
27
31
36
40
40
56
有序链表的效率:
有序链表插入数据效率为O(N),但查找跟删除最大数据就是表头数据效率为O(1).所以在最小数据存储频繁,但又不需要快速插入的时候
有序链表是个不错的选择.
有序链表排序较插入排序效率也要好些.因为他的复制次数仅有两次.一次从数组取出,一次放回数组.