Java 双向链表
/**
* 双向链表
*
*/
public class TwoWayLinkedList {
private Node head;
private Node tail;
private int size;
private class Node {
private Object data;
private Node next;
private Node pre;
public Node (Object data) {
this.data = data;
}
}
public TwoWayLinkedList() {
size = 0;
head = null;
tail = null;
}
//添加头部节点
public void addHead(Object data) {
Node node = new Node(data);
if(size == 0) {
head = node;
tail = node;
size ++;
}else {
head.pre = node;
node.next = head;
head = node;
size++;
}
}
//添加尾部节点
public void addTail(Object data) {
Node node = new Node(data);
if(size == 0) {
head = node;
tail = node;
size++;
}else {
node.pre = tail;
tail.next = node;
tail = node;
size++;
}
}
//删除链表头
public Node deleteHead() {
Node temp = head;
if(size != 0) {
head = head.next;
head.pre = null;
size--;
}
return temp;
}
//删除链表尾
public Object deleteTail() {
Node temp = tail;
if(size != 0) {
tail = tail.pre;
tail.next = null;
size--;
}
return temp;
}
//获得链表的节点个数
public int getSize(){
return size;
}
//判断链表是否为空
public boolean isEmpty(){
return (size == 0);
}
public void display() {
if(size > 0) {
Node node = head;
int tempSize = size;
if(tempSize == 1) {
System.out.println("["+node.data+"]");
return;
}
while(tempSize > 0) {
if(node.equals(head)) {
System.out.print("["+node.data+"->");
}else if(node.next == null) {
System.out.print(node.data+"]");
}else {
System.out.print(node.data+"->");
}
node = node.next;
tempSize--;
}
System.out.println();
}else {
System.out.println("[]");
}
}
}
测试:
public class TestTwoWayLinkedList {
@Test
public void testTwoWayLinkedList() {
TwoWayLinkedList link = new TwoWayLinkedList();
link.addHead("A");
link.addHead("B");
link.addHead("C");
link.addHead("D");
link.addTail("E");
link.addTail("F");
link.addTail("G");
link.display();
link.deleteHead();
link.display();
link.deleteTail();
link.display();
}
}
结果;
[D->C->B->A->E->F->G]
[C->B->A->E->F->G]
[C->B->A->E->F]