package 链表;
import java.util.Iterator;
public class DoubleLink implements Iterable{
private int size;
private Node first;//头结点
private Node last=first;
/**
*
* 节点内部类
*
*/
private class Node{
Object data;
Node next;
Node pre;
public Node(Object data,Node pre,Node next){
this.data=data;
this.pre=pre;
this.next=next;
}
}
public boolean isEmpty(){
return (0 == size) ? true : false;
}
/**
* 根据指定索引查找节点
* @param index
* @return
*/
private Node node(int index){
if(index<=size/2){
Node c=first;
for(int i=0;i<index;i++){
c=c.next;
}
return c;
}
else{
Node c=last;
for(int i=size-1;i>index;i--){
c=c.pre;
}
return c;
}
}
/**
* 添加方法
* @param obj
*/
public void add(Object obj){
Node newNode=new Node(obj,null,null);
if(first==null){
first=newNode;
last=first;
}else{
last.next=newNode;
newNode.pre=last;
last=newNode;
}
size++;
}
public Object get(int index){
this.checkIndex(index);
return node(index).data;
}
/**
* 检查下标是否正确的方法
* @param index
*/
private void checkIndex(int index){
if(index<0){
throw new IndexOutOfBoundsException("is negative number! "+index);
}
if(index>=size){
throw new IndexOutOfBoundsException("index out of bounds "+index);
}
}
/**
* 返回大小的方法
* @return
*/
public int size(){
return size;
}
private class Iter implements Iterator{
private Node cNode=first;
private int cursor=0;
@Override
public boolean hasNext() {
return cursor!=size;
}
@Override
public Object next() {
Object o=cNode.data;
cNode=cNode.next;
cursor++;
return o;
}
}
@Override
public Iterator iterator() {
return new Iter() ;
}
/**
* 在指定位置插入一个新的节点
* @param obj
*/
public void insert(Object obj,int index){
this.checkIndex(index);
if(index==0){
Node newNode=new Node(obj,null,null);
newNode.next=first;
}else{
Node target=node(index);
Node newNode=new Node(obj,target.pre,target);
target.pre.next=newNode;
target.pre=newNode;
}
size++;
}
/**
* 删除指定位置节点
* @param index
*/
public void delete(int index){
this.checkIndex(index);
Node target=node(index-1);
Node target1=target.next;
target.next=target1;
target1.pre=target;
size--;
}
}
双向链表
最新推荐文章于 2024-09-13 11:50:55 发布