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

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

直接式:package com.ds.link;

public class DoubleLink {

/**

* Node类定义了双向链表中节点的结构,它是一个私有类,

* 而其属性和构造函数都是公有的,这样,其父类可以直接访问其属性

* 而外部类根本不知道Node类的存在。

* @author ZHB

*

* @param 类型

* @param Data 是节点中的数据

* @param pre 指向前一个Node节点

* @param next 指向后一个Node节点

*/

private class Node{

public Node pre;

public Node next;

public T data;

public Node(T data,Node pre,Node 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 Header;

private Node Tail;

/*

* 构造函数

* 我们构造了一个带有头、尾节点的双向链表

* 头节点的Next指向尾节点

* 为节点的pre指向头节点

* 链表长度起始为0。

*/

public DoubleLink(){

theSize = 0;

Header = new Node(null,null,null);

Tail = new Node(null,Header,null);

Header.next = Tail;

}

public void add(T item){

Node aNode = new Node(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 current = Header.next;

for(int i = 0;i < index;i++){

current = current.next;

}

return current.data;

}

public void print(){

Node current = Header.next;

while(current.next != null){

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

current = current.next;

}

}

public static void main(String[] args){

DoubleLink dLink= new DoubleLink();

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值