Java双向链表结构(环形):
/**
* two way linked list
* @param <E>
*/
public class TwoWayLink<E> {
private Node first, last;
private int size;
private void insert(Node insert) {
if (isEmpty()) {
first = insert;
last = insert;
} else {
insert.next = first;
insert.prev = last;
first.prev = insert;
last.next = insert;
}
size ++;
}
/**
* head node insert
* @param e
*/
public void insertFirst (E e) {
Node insert = new Node(e);
insert(insert);
first = insert;
}
/**
* tail node insert
* @param e
*/
public void insertLast (E e) {
Node insert = new Node(e);
insert(insert);
last = insert;
}
/**
* check node
* @return
*/
public E peek () {
if (isEmpty()) throw new NullPointerException("the link is empty, error.");
return first.e;
}
public void display () {
if (isEmpty()) throw new NullPointerException("the link is empty, error.");
Node tmp = first;
tmp = tmp.next;
while (tmp!=first) {
tmp = tmp.next;
}
}
public boolean isEmpty () {
return first == null;
}
public int getSize (){
return size;
}
class Node {
E e;
Node prev, next;
public Node(E e) {
this.e = e;
}
}
}
Java双向链表结构(普通):
/**
* normal two way linked list
* @param <E>
*/
public class TwoWayLink2<E> {
private int size;
private Node first, last;
/**
* insert head node
* @param e
*/
public void linkedHead (E e) {
Node newNode = new Node(e);
if (initLinked(newNode)) return;
newNode.next = first;
first.prev = newNode;
first = newNode;
size ++;
}
/**
* insert tail node
* @param e
*/
public void linkedTail (E e) {
Node newNode = new Node(e);
if (initLinked(newNode)) return;
last.next = newNode;
newNode.prev = last;
last = newNode;
size ++;
}
/**
* remove head node
* @return
*/
public E removeHead () {
checkNull();
Node node = first;
first = node.next;
return node.e;
}
/**
* remove tail node
* @return
*/
public E removeTail () {
checkNull();
Node node = last;
last = node.prev;
return node.e;
}
private void checkNull () {
if (size <= 0) throw new IllegalStateException("the linked is empty, error.");
}
/**
* init linked list
* @param newNode
* @return
*/
private boolean initLinked (Node newNode) {
if (isEmpty()) {
first = newNode;
last = newNode;
size ++;
return true;
}
return false;
}
public boolean isEmpty () {
return first == null;
}
public int getSize () {
return size;
}
/**
* linked iterator
* @return
*/
public Iterator getIterator() {
if (isEmpty()) return null;
return new Iterator(first);
}
class Iterator {
Node current;
public Iterator(Node current) {
this.current = current;
}
Node next (){
return current.next;
}
}
class Node {
E e;
Node prev, next;
public Node(E e) {
this.e = e;
}
}
}