获取指定索引数据:public E get(int index)
链表可以像数组一样进行处理,所以也应该可以像数组一样进行索引数据取得,在这样的情况下就可以继续利用递归的形式来完成。
- 在Link接口追加新的方法
- 在子类中覆写该方法
- 在Node类中追加根据索引获取数据的处理
class JavaDemo
{
public static void main(String[] args)
{
ILink<String> all = new LinkImpl<String>();
all.add("Heool");
all.add("World");
Object[] result = all.toArray();
for(Object x : result){
System.out.println(x);
}
System.out.println("------------------数据获取的分割线-------------------");
System.out.println(all.get(0));
}
}
interface ILink<E> //设置泛型避免安全隐患
{
public void add(E e);
public int size(); //获取数组的个数
public boolean isEmpty(); //判断是否为空集合
public Object[] toArray(); //变成数据形式的方法
public E get(int index); //按照索引提取数据的方法
}
class LinkImpl<E> implements ILink<E>
{
private class Node //保存节点的数据关系
{
private E data; //保存的数据
private Node next; //下一个节点
public Node(E data){ //有数据的情况下才有意义
this.data = data;
}
//第一次调用:LinkImpl.root.addNode(),this = LinkImpl.root
//第二次调用:LinkImpl.root.next.addNode(),this = LinkImpl.root.next
public void addNode(Node newNode){ //保存新的Node数据
if(this.next == null){ //root的下一个节点为空
this.next = newNode;
}else{ //如果已经有节点了
this.next.addNode(newNode); //利用递归继续往后查询直到遇到空节点
}
}
//第一次调用:this = LinkImpl.root
//第二次调用:this = LinkImpl.root.next
public void toArrayNode(){
LinkImpl.this.returnData[LinkImpl.this.foot++] = this.data;
if (this.next != null) //还有下一个数据
{
this.next.toArrayNode();
}
}
public E getNode(int index){
if(LinkImpl.this.foot == index){ //索引相同
return this.data; //返回当前数据
}else{
return this.next.getNode(index); //递归调用
}
}
}
//----------以下为LinkImpl类中定义的成员-----------
private Node root; //保存根元素
private int count; //保存数据的个数
private int foot = 0; //操作数组的脚标
private Object[] returnData; //返回的数组
//----------以下为LinkImpl类中定义的方法-----------
public void add(E e){
if(e == null){ //保存的数据为null
return; //方法调用直接结束
}
//数据本身是不具备关联性的,只有Node类有,那么想实现关联处理就必须将数据封装在Node类中
Node newNode = new Node(e); //创建一个新的节点
if(this.root == null){ //现在没有根节点
this.root = newNode;//第一个节点作为根节点
}else{ //根节点存在
this.root.addNode(newNode); //把创建的新节点交给Node类自行判断放在合适的位置
}
this.count++;//每传入一个对象都会增加
}
//获取长度的方法
public int size(){
return this.count;
}
public boolean isEmpty(){
return this.count == 0;//数组长度是否为0
}
//获取数组的方法
public Object[] toArray(){
if(this.isEmpty()){ //空集合
return null;//没有数据
}
this.foot = 0; //脚标清零
this.returnData = new Object[this.count];//根据已有的长度开辟数组
this.root.toArrayNode();//利用Node类进行递归数据获取
return this.returnData;
}
//获取指定索引位置内容的方法
public E get(int index){
if(index >= this.count){ //索引应该在指定范围之内
return null;
}
//索引数据的获取应该有Node类完成
this.foot = 0;//重置索引的下标
return this.root.getNode(index);
}
}
结果:
Heool
World
------------------数据获取的分割线-------------------
Heool
这一点和数组是很相似的,但是需要注意的是,数组获取一个数据的时间复杂度为1 ,而链表获取的数据的时间复杂度为n。