链表之有序链表

对于某些应用程序中链表中的数据保持有序性是有必要的。具有这个特性的链表叫做有序链表。有序链表的删除操作通常只限于删除链表头部,有时候也用find()方法删除链表中的特性元素。

一般说来在所有可以使用有序数组的场合都可以使用有序链表来代替,有序链表对于有序数组的优越性在于插入操作不需要进行数据移动,并且可以实现动态内存分配。

有序链表也可以实现优先级队列。

有序链表的java实现:

      
public class SortedList {
Node firstNode;
public SortedList(){
firstNode = null;
}
public boolean isEmpty(){
return firstNode == null;
}
public void addNode(String value){
Node node = new Node(value);
if(isEmpty()){
firstNode = node;
}else {
Node proNode = null;
Node currNode = firstNode;
while(currNode!=null&&Integer.parseInt(currNode.showValue())>Integer.parseInt(value)){
proNode = currNode;
currNode= currNode.getNext();
}
if(currNode == null){
proNode.setNext(node);
}else if (currNode==firstNode) {
node.setNext(firstNode);
firstNode = node;
}else {
node.setNext(currNode);
proNode.setNext(node);
}
}
}
public void delFirst(){
if(isEmpty()){
return;
}else {
firstNode = firstNode.getNext();
}
}
public void show(){
if(isEmpty()){
return;
}else {
Node node = firstNode;
while (node!=null) {
System.out.print(node.showValue()+" ");
node = node.getNext();
}
System.out.println();
}
}
}
测试代码


SortedList sList = new SortedList();
Random r = new Random();
for(int i =0;i<10;i++){
int x = r.nextInt(100);
sList.addNode(x+"");
}
sList.show();
sList.delFirst();
sList.show();


测试结果

88 78 68 59 43 39 25 7 6 0
78 68 59 43 39 25 7 6 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值