链表很灵活,长度不固定,分散存储弥补了数组长度固定的不足。链表有单链表,双向链表,循环链表等
我就写了个双向链表,实现了一些简单功能~
队列和栈可以用链表的形式和数组的形式实现,两者的区别在于前者的存储空间是分散的,后者是连续并且固定的。
一、实现双向链表
/**
* @author linqh0806
* @param <U>
*/
public class DoubleLinkedList<U> {
public static class Node<T> {
private Node<T> pre;
private Node<T> next;
private T val;
public Node() {
this.val = null;
this.pre = null;
this.next = null;
}
public Node(T val, Node<T> pre, Node<T> next) {
this.val = val;
this.pre = pre;
this.next = next;
}
}
private Node<U> nil;
private int size;
private Node<U> head;
public DoubleLinkedList() {
this.size = 0;
this.nil = new Node();
nil.next = nil;
nil.pre = nil; // 保证链表安全,在初始化链表为空时,插入数据不会报空指针错误
}
/**
* 在链表头插入数据
* @param val
*/
public void insert(U val) {
Node<U> newNode = new Node<U>();
newNode.val = val;
newNode.next = nil.next;
newNode.pre = nil;
nil.next.pre = newNode;
nil.next = newNode;
size++;
}
/**
* 删除链表中的node
* @param node
* @return
*/
public boolean delete(Node<U> node) {
Node