/**
* 双向循环链表测试
* @author coach
* @param <E>
*/
public class Node<E>
{
private E element; //结点数据
private Node<E> next; //上结点
private Node<E> previous; //下结点
private static int size=0; //链表长
//默认关结点next previous都是空,
public Node()
{
this.element=null;
this.next=null;
this.previous=null;
}
private Node(E element,Node<E> next,Node<E> previous)
{
this.element=element;
this.next=next;
this.previous=previous;
}
/**
* 尾部添加元素 e
* @param e
*/
public void addAfter(E e)
{
//定义新结点,next-->头结点;previous-->头结点.previous(尾结点)
Node<E> newNode=new Node<E>(e,this,this.previous==null?this:this.previous);
//头结点next为空则让它指向newNode
if(this.next==null)
{
this.next=newNode;
}
//头结点previous为空则让它指向newNode
if(this.previous==null)
{
this.previous=newNode;
}
this.previous.next=newNode;
this.previous=newNode;
size++;
}
/**
* 头部添加元素 e
* @param e
*/
public void addBefor(E e)
{
Node<E> newNode=new Node<E>(e,this.next==null?this:this.next,this);
if(this.next==null)
{
this.next=newNode;
}
if(this.previous==null)
{
this.previous=newNode;
}
this.next.previous=newNode;
this.next=newNode;
size++;
}
/**
* 在index处添加元素e
* @param e
* @param index
*/
public void add(E e,int index)
{
//索引越界
if(index>=size || index<0)
{
throw new IndexOutOfBoundsException("Node.get():"+index);
}
else
{
//index>size/2,反向遍历
if(index>size>>1)
{
Node<E> temp=this;
for(int i=size;i>index;i--)
{
temp=temp.previous;
}
Node<E> newNode=new Node<E>(e,temp,temp.previous);
temp.previous.next=newNode;
temp.previous=newNode;
}
else
{
Node<E> temp=this;
for(int i=0;i<=index;i++)
{
temp=temp.next;
}
Node<E> newNode=new Node<E>(e,temp,temp.previous);
temp.previous.next=newNode;
temp.previous=newNode;
}
size++;
}
}
/**
* 删除第index个元素
* @param index
*/
public void remove(int index)
{
//索引越界
if(index>=size || index<0)
{
throw new IndexOutOfBoundsException("Node.get():"+index);
}
else
{
//index>size/2,反向遍历
if(index>size>>1)
{
Node<E> temp=this;
for(int i=size;i>index;i--)
{
temp=temp.previous;
}
temp.previous.next=temp.next;
temp.next.previous=temp.previous;
}
else
{
Node<E> temp=this;
for(int i=0;i<=index;i++)
{
temp=temp.next;
}
temp.previous.next=temp.next;
temp.next.previous=temp.previous;
}
size--;
}
}
/**
* 取得第index个元素
* @param index
* @return
*/
public E get(int index)
{
//索引越界
if(index>=size || index<0)
{
throw new IndexOutOfBoundsException("Node.get():"+index);
}
else
{
//index>size/2,反向遍历
if(index>size>>1)
{
Node<E> temp=this;
for(int i=size;i>index;i--)
{
temp=temp.previous;
}
return temp.element;
}
else
{
Node<E> temp=this;
for(int i=0;i<=index;i++)
{
temp=temp.next;
}
return temp.element;
}
}
}
public int size()
{
return size;
}
public static void main(String a[])
{
Node node=new Node();
node.addAfter("1");
node.addAfter("2");
node.addAfter("3");
node.addBefor("0");
node.add("7", 0);
System.out.println(node.get(0) );
System.out.println(node.get(1) );
System.out.println(node.get(2) );
System.out.println(node.get(3) );
System.out.println(node.get(4) );
}
}
LinkedList学习(双向循环链表)
最新推荐文章于 2022-12-20 20:51:09 发布