您的位置:首页 > 理论基础 > 数据结构算法

【Java数据结构】2.2双向链表的简单实现

2013-09-04 16:59 363 查看
按链表的组织形式分有ArrayList和LinkList两种。ArrayList内部其实是用数组的形式实现链表,比较适合链表大小确定或较少对链表进行增删操作的情况,同时对每个链表节点的访问时间都是constant;而LinkList内部以一个List实现链表,比较适合需要频繁对链表进行操作的情况,对链表节点的访问时间与链表长度有关O(N)。
另外,根据实现形式可以分为直接式(想不出什么合适的名字,姑且这样吧)和使用Iterator(迭代模式)两种方法。
直接式的实现方法和C/C++中的写法差不多; 而使用Iterator时,需要实现java.lan中的Iterable接口(或者也可以自己在链表内部定义自己的Iterator method)将在下章博客中介绍:直接式:
package com.ds.link;
public class DoubleLink <T>{

/**
* Node<AnyType>类定义了双向链表中节点的结构,它是一个私有类,
* 而其属性和构造函数都是公有的,这样,其父类可以直接访问其属性
* 而外部类根本不知道Node类的存在。
* @author ZHB
*
* @param <T> 类型
* @param Data 是节点中的数据
* @param pre  指向前一个Node节点
* @param next 指向后一个Node节点
*/
private class Node<T>{
public Node<T> pre;
public Node<T> next;
public T data;
public Node(T data,Node<T> pre,Node<T> next){
this.data = data;
this.pre = pre;
this.next = next;
}
public Node(){
this.data = null;
this.pre = null;
this.next = null;
}
}

// 下面是DoubleLinkedList类的数据成员和方法
private int theSize;
private Node<T> Header;
private Node<T> Tail;

/*
* 构造函数
* 我们构造了一个带有头、尾节点的双向链表
* 头节点的Next指向尾节点
* 为节点的pre指向头节点
* 链表长度起始为0。
*/
public DoubleLink(){

theSize = 0;
Header = new Node<T>(null,null,null);
Tail = new Node<T>(null,Header,null);

Header.next = Tail;
}

public void add(T item){

Node<T> aNode = new Node<T>(item,null,null);

Tail.pre.next = aNode;
aNode.pre = Tail.pre;
aNode.next = Tail;
Tail.pre = aNode;

theSize++;
}

public boolean isEmpty(){
return (this.theSize == 0);
}

public int size(){
return this.theSize;
}

public T getInt(int index){

if(index > this.theSize - 1 || index < 0)
throw new IndexOutOfBoundsException();

Node<T> current = Header.next;

for(int i = 0;i < index;i++){
current = current.next;
}

return current.data;
}

public void print(){

Node<T> current = Header.next;

while(current.next != null){

System.out.println(current.data.toString());

current = current.next;
}

}

public static void main(String[] args){
DoubleLink<String> dLink= new DoubleLink<String>();

dLink.add("zhb");
dLink.add("zzb");
dLink.add("zmy");
dLink.add("zzj");

System.out.println("size : " + dLink.size());
System.out.println("isEmpty? : " + dLink.isEmpty());
System.out.println("3 : " + dLink.getInt(2));
dLink.print();
}
}
运行结果:

size : 4
isEmpty? : false
3 : zmy
zhb
zzb
zmy
zzj


有什么问题,我们随时沟通!

本文出自 “CEO之路” 博客,请务必保留此出处http://zhaohaibo.blog.51cto.com/7808533/1288669
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: