Java 双向列表
public class DoubleLink<T> {
private int size = 0;
private Node head;//头节点
static class Node<T> {
Node<T> prev;
Node<T> next;
T value;
public Node(T value) {
this.prev = null;
this.next = null;
this.value = value;
}
}
public DoubleLink() {
}
public boolean isEmtity(Node head) {
return null == head ? true : false;
}
/**
* 这个是一直从尾部添加节点
* @param value
*/
public void add(T value) {
Node<T> node = new Node<>(value);
if (isEmtity(head)) {
head = node;
size++;
return;
}
Node cru = head;
while (null != cru.next) {
//我们去找节点的最后一个节点 看是不是为null 如果为null 我们就认为是最后一个节点 在该节点后面追加新的节点
cru = cru.next;
}
cru.next = node;
node.prev = cru;
size++;
}
/**
* 头节点加入 这是一个列表结构 很典型的列子 很多算法用的这个 比如 LRU 算法
*/
public void headAdd(T value) {
Node<T> node = new Node<>(value);
if (isEmtity(head)) {
head = node;
size++;
return;
}
head.prev = node;
node.next = head;
head = node;
size++;
}
public T getValue(int index) {
if (isEmtity(head)) {
return null;
}
if (size < index) {
throw new IndexOutOfBoundsException();
}
Node<T> node = forEach(head,index);
return node.value;
}
public Node forEach(Node head,int index) {
Node cru = head;
for (int i = 0; i < index; i++) {
cru = cru.next;
}
return cru;
}
public static void main(String[] args) {
DoubleLink<Integer> doubleLink = new DoubleLink<>();
doubleLink.headAdd(1);
doubleLink.headAdd(2);
doubleLink.headAdd(3);
doubleLink.headAdd(4);
System.out.println(doubleLink.getValue(0));
}
}
846

被折叠的 条评论
为什么被折叠?



