按链表的组织形式分有ArrayList和LinkList两种。ArrayList内部其实是用数组的形式实现链表,比较适合链表大小确定或较少对链表进行增删操作的情况,同时对每个链表节点的访问时间都是constant;而LinkList内部以一个List实现链表,比较适合需要频繁对链表进行操作的情况,对链表节点的访问时间与链表长度有关O(N)。另外,根据实现形式可以分为直接式(想不出什么合适的名字,姑且这样吧)和使用Iterator(迭代模式)两种方法。直接式的实现方法和C/C++中的写法差不多;而使用Iterator时,需要实现java.lan中的Iterable接口(或者也可以自己在链表内部定义自己的Iterator method)将在下章博客中介绍:
直接式:package com.ds.link;
public class DoubleLink {
/**
* Node类定义了双向链表中节点的结构,它是一个私有类,
* 而其属性和构造函数都是公有的,这样,其父类可以直接访问其属性
* 而外部类根本不知道Node类的存在。
* @author ZHB
*
* @param 类型
* @param Data 是节点中的数据
* @param pre 指向前一个Node节点
* @param next 指向后一个Node节点
*/
private class Node{
public Node pre;
public Node next;
public T data;
public Node(T data,Node pre,Node next){
this.data = data;
this.pre = pre;
this.next = next;
}
public Node(){
this.data = null;
this.pre = null;
this.next = null;
}
}
// 下面是DoubleLinkedList类的数据成员和方法
private int theSize;
private Node Header;
private Node Tail;
/*
* 构造函数
* 我们构造了一个带有头、尾节点的双向链表
* 头节点的Next指向尾节点
* 为节点的pre指向头节点
* 链表长度起始为0。
*/
public DoubleLink(){
theSize = 0;
Header = new Node(null,null,null);
Tail = new Node(null,Header,null);
Header.next = Tail;
}
public void add(T item){
Node aNode = new Node(item,null,null);
Tail.pre.next = aNode;
aNode.pre = Tail.pre;
aNode.next = Tail;
Tail.pre = aNode;
theSize++;
}
public boolean isEmpty(){
return (this.theSize == 0);
}
public int size(){
return this.theSize;
}
public T getInt(int index){
if(index > this.theSize - 1 || index < 0)
throw new IndexOutOfBoundsException();
Node current = Header.next;
for(int i = 0;i < index;i++){
current = current.next;
}
return current.data;
}
public void print(){
Node current = Header.next;
while(current.next != null){
System.out.println(current.data.toString());
current = current.next;
}
}
public static void main(String[] args){
DoubleLink dLink= new DoubleLink();
dLink.add("zhb");
dLink.add("zzb");
dLink.add("zmy");
dLink.add("zzj");
System.out.println("size : " + dLink.size());
System.out.println("isEmpty? : " + dLink.isEmpty());
System.out.println("3 : " + dLink.getInt(2));
dLink.print();
}
}
运行结果:
size : 4
isEmpty? : false
3 : zmy
zhb
zzb
zmy
zzj
有什么问题,我们随时沟通!