今天聊的是ArrayList类的实现。
Node类:
public class Node {
public Node(Object data, Node next) {
super();
this.data = data; //数据域初始化
this.next = next; //指向下一个节点初始化
}
public Object getData() {
return data; //得到数据域
}
public void setData(Object data) {
this.data = data; //设置数据域
}
public Node getNext() {
return next; //得到下一个节点的指针
}
public void setNext(Node next) {
this.next = next; //设置下一个节点的指针
}
private Object data; //数据域
private Node next; //下一个节点
}
LinkedList类:
public class LinkedList {
Node head = null; //头结点
Node tail = null; //尾节点
int size = 0; //链表的长度
public void add(Object o) { //向链表添加节点的函数
Node n = new Node(o, null); //新建一个节点
if(head == null) { //如果头结点为空,则指向将头结点和和尾节点指向新节点
head = n;
tail = n;
}
tail.setNext(n); //不为空就将尾节点指向新节点
tail = n; //<span style="font-family: Arial, Helvetica, sans-serif;">,并更新尾节点</span>
size ++; //链表长度计数
}
public int size() {
return size; //返回链表长度
}
}
测试:
将Iterator(1)文章中的Test类中的ArrayList al = new ArrayList()改为LinkedList al = new LinkedList()。
就ok了。