关于java双连表的实现
java双链接属于数据结构的范畴,用途广泛,这里为handler的message的数据结构(单链表)做个铺垫 .
Tip: 这里可以将java的”=” 当作c语言的”->”,更方便理解
import java.util.Iterator;
//实现Iterable是为了使用增强for
public class MyDoubleLink implements Iterable<Object>{
//定义节点
private class Node{
public Node(Object data){
this.data = data;
}
Node next;
Node prev;
Object data;
}
//定义两个首尾指针,分别指向头结点和尾节点
private Node head;
private Node rear;
//添加节点的方法
public void add(Object data){
Node node = new Node(data);
//空链表添加元素
if (head == null){
head = node;
rear = node;
} else {
//在有头结点的情况下添加,下面的代码自己画图更清楚
rear.next = node;
node.prev = rear;
rear = node;
}
}
public boolean contains(Object data){
Node node = find(data);
return node != null;
}
public void print(){
Node temp = head;
while(temp != null){
System.out.print(temp.data + ",");
temp = temp.next;
}
System.out.println();
}
//这里不能用public的修饰方法,因为Node为private
//找到指定的节点
private Node find(Object data){
Node node = head;
while (node != null){
//比较元素是否相等的最全写法,equals和hascode,可以参照HashSet的源码(HashSet存储自定义对象保证元素唯一性)
if (node.data.equals(data) && node.data.hashCode() == data.hashCode()){
break;
} else {
node = node.next;
}
}
return node;
}
//删除指定及节点
public void remove(Object data){
Node node = find(data);
if (node != null){
if (node == head && node == rear){//只有一个节点
head = null;
rear = null;
} else if (node == head){ //头节点
head = head.next;
head.prev = null;
} else if (node == rear){ //尾节点
rear = rear.prev;
rear.next = null;
} else { //中间节点
node.prev.next = node.next;
node.next.prev = node.prev;
}
}
}
//从杂牌军变成正规军的方法(为了使用增强for)
@Override
public Iterator<Object> iterator() {
Iterator<Object> ite = new Iterator<Object>() {
private Node temp = head;
@Override
public boolean hasNext() {
return temp != null;
}
@Override
public Object next() {
// TODO Auto-generated method stub
Object data = temp.data;
temp = temp.next;
return data;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
};
return ite;
}
}
下面是测死类
public class Test {
public static class Instance{
public Instance(int i){
}
public Instance(){
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Instance in = new Instance(){
};
MyDoubleLink datas = new MyDoubleLink();
datas.add("aaa");
datas.add("bbb");
datas.add("ccc");
datas.print();
datas.remove("ccc");
datas.print();
for (Object d : datas) {
System.out.println(d);
}
}
}