双节点类:
public class DoubleNode<T> { public T data; public DoubleNode<T> prev, next; public DoubleNode(T data, DoubleNode<T> prev, DoubleNode<T> next) { this.data = data; this.prev = prev; this.next = next; } public DoubleNode(T data) { this.data = data; } public DoubleNode() { } }
循环双节点链表:
/* * 循环双链表最后一个头结点的next链指向头结点 * 头结点的prev链指向最后一个节点 */ public class CirDoublyList<T> { public DoubleNode<T> head; /* * 构造空的循环双链表 */ public CirDoublyList() { this.head = new DoubleNode<T>(); this.head.prev = this.head; this.head.next = this.head; } /* * 判断双链表是否为空 */ public boolean isEmpty() { return this.head.next == this.head; } /* * 将x插入为第i个元素,x!=null,返回x节点 对i容错,若i<0,则头插入,若i>长度n,则尾插入 时间复杂度O(n) */ public DoubleNode<T> insert(int i, T x) { if (x == null) throw new NullPointerException("x==null"); // x为空,则抛出空异常 DoubleNode<T> front = this.head; for (int j = 0; front.next != this.head && j < i; j++) // 寻找第i-1个,或最后一个节点 front = front.next; DoubleNode<T> q = new DoubleNode<T>(x, front, front.next); front.next.prev = q; front.next = q; return q; } /* * 尾插入x元素,返回x节点,算法在头结点之前插入 时间复杂度为O(1) */ public DoubleNode<T> insert(T x) { if (x == null) throw new NullPointerException("x==null"); DoubleNode<T> q = new DoubleNode<T>(x, head.prev, head); head.prev.next = q; head.prev = q; return q; } /* * 返回所有元素的描述字符串(元素次序从后向前 ) 方法体省略了,有时间再补充 */ public String toPreviousString() { return "null"; } /* * 移除最后一个元素,方法体暂时省略 */ public void removeLast() { } public static void main(String[] args) { // TODO Auto-generated method stub } }参考书籍:《数据结构(java版)》叶核亚,有不懂的,可以再看一下这本书