之前说到了单向链表,下面是有序单向链表;顾名思义,有序单向链表是排好序的单向链表,大部分操作和单向链表一样,只是插入略有不同;
插入时需先找到节点在链表中插入的位置;
下面是具体的实现,该类继承了之前的SortedSinglyLinkedList类,重写了insert()方法,可参考之前的文章“java实现单向链表”
package com.zxd.link;
import java.util.Random;
/**
* SortedSinglyLinkedList:Java实现有序单向链表(假设是按升幂排序) 有序单向链表和单向链表类似,只有插入的方法不一样:
* 插入之前,先得找到比插入节点值大的节点 ;此处只实现insert(Node node)方法;
*
* @author zeng.xiangdong 1770534116@qq.com
* @version V1.0 2014-6-30 下午11:10:14
*/
public class SortedSinglyLinkedList extends SinglyLinkedList {
/**
* Creates a new instance of SortedSinglyLinkedList.
*
* @param data
*/
public SortedSinglyLinkedList(int data) {
super(data);
}
/**
* insert:插入
*
* @param node 要插入的节点
*/
private void insert(SinglyLinkedNode node) throws Exception {
SinglyLinkedNode currentNode;
SinglyLinkedNode preNode = null;
if(headNode == null) {
throw new Exception("null link list");
} else {
currentNode = headNode;
while(hasNext(currentNode)) {
if(currentNode.getData() >= node.getData()) {
node.setNextNode(currentNode);
preNode.setNextNode(node);
return;
}
preNode = currentNode;
currentNode = currentNode.getNextNode();
}
// 已经到了最尾,则和最尾的比较
if(currentNode.getData() >= node.getData()) {
node.setNextNode(currentNode);
preNode.setNextNode(node);
} else {
// 在最尾插入
node.setNextNode(null);
currentNode.setNextNode(node);
}
} // end of else
}
/**
* main:测试main方法
*
* @param args
*/
public static void main(String[] args) throws Exception {
// 初始化链表
SortedSinglyLinkedList list = new SortedSinglyLinkedList(0);
Random random = new Random();
for(int i = 1; i < 10; i++) {
list.insert(new SinglyLinkedNode(random.nextInt(100)));
}
// 输出链表
System.out.print("list : ");
for(int i = 0; i < 10; i++) {
System.out.print(list.getNodeByIndex(i) + " ");
}
System.out.println();
}
}
输出结果:
list : 0 1 41 56 59 62 76 77 81 90