双链表的原理图形如下:
其java实现的代码:
/**
* 双向链表
*/
public class MyLinkList {
private Node first;// 指向第一个结点
private Node last; // 指向最后的一个结点
private int size = 0;// 链表中结点的个数
public int getSize() {
return size;
}
// 链表的最后一个元素增加结点
public void AddLast(Object ele) {
Node node = new Node(ele);
if (size == 0) {
// 第一个结点
this.first = node;
this.last = node;
} else {
this.last.next = node;
node.pre = this.last;
this.last = node;
}
size++;
}
// 链表的第一个元素的增加结点
public void AddFirst(Object ele) {
Node node = new Node(ele);
if (size == 0) {
this.first = node;
this.last = node;
} else {
this.first.pre = node;
node.next = this.first;
this.first = node;
}
size++;
}
//删除链表中的某一个结点
public void delete(Object obj) {
if (size == 0) {
return;
}
//第一个结点
if (obj.equals(this.first.ele)) {
this.first = this.first.next;
size--;
} else {
Node current = this.first;
while (current.next != null) {
if (obj.equals(current.ele)) {
current.pre.next = current.next;
current.next.pre=current.pre;
size--;
}
current = current.next;
}
//最后一个结点
if (obj.equals(this.last.ele)) {
this.last.pre.next = null;
this.last = this.last.pre;
size--;
}
}
}
//把链表中的结点用另一个节点替换
public void update(Object srcObj,Object destObj){
Node current = this.first;
if (srcObj.equals(this.last.ele)) {
this.last.ele=destObj;
}
while (current.next != null) {
if (srcObj.equals(current.ele)) {
current.ele=destObj;
}
current = current.next;
}
}
// 查询链表中的某一个元素
public boolean select(Object obj) {
Node current = this.first;
if (obj.equals(this.last.ele)) {
return true;
}
while (current.next != null) {
if (obj.equals(current.ele)) {
return true;
}
current = current.next;
}
return false;
}
//打印出链表中的所有元素
public String showAll() {
if (size == 0) {
return null;
}
Node current = this.first;
StringBuffer sb = new StringBuffer();
sb.append(current.ele);
while (current.next != null) {
if (this.last != current)
sb.append("-->");
current = current.next;
sb.append(current.ele);
}
return sb.toString();
}
class Node {
Node pre; // 前一个结点
Node next; // 后一个结点
Object ele; // 结点的数据
public Node(Object ele) {
super();
this.ele = ele;
}
}
}