//双向链表类
publicclassDoubleLinkList{
//结点类
publicclassNode{
publicObject data;
publicNode next;
publicNode prior;
publicNode(Object obj,Node next,Node prior){
this.data = obj;
this.next = next;
this.prior = prior;
}
}
Node head; //记录头结点信息即可(头结点下标为-1)
int size;
//初始化一个空链表
publicDoubleLinkList(){
//初始化头结点,让头指针指向头结点。并且让当前结点对象等于头结点。
this.head =newNode(null, null, null);
this.size =0;
}
//定位
publicNode locate(int index) throws Exception
{
//容错性
if(index <-1|| index > size)
thrownewException("参数错误!");
//定位到temp指向第index个(index为下标,从0开始)
Node temp = head;
for(int i =-1; i < index; i++)
if(temp != null)
temp = temp.next;
return temp;
}
publicvoiddelete(int index) throws Exception{
if(isEmpty())
thrownewException("链表为空,无法删除!");
if(index <0|| index > size -1)
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
temp.next = temp.next.next;
if(temp.next != null) //当删除到最后一个元素:temp.next == null
temp.next.prior = temp;
size--;
}
publicvoid insert(int index,Object obj) throws Exception{
//容错性
if(index <0|| index > size )
thrownewException("参数错误!");
Node temp = locate(index -1); //定位到要操作结点的前一个结点对象
Node p =newNode(obj,temp.next,temp);
temp.next = p;
if(p.next != null) //当插入到最后一个位置:p.next == null
p.next.prior = p;
size++;
}
public boolean isEmpty(){
return size ==0;
}
publicint size(){
returnthis.size;
}
}
publicclassTest{
publicstaticvoid main(String[] args) throws Exception{
DoubleLinkListlist=newDoubleLinkList();
for(int i =0; i <10; i++){
int temp =((int)(Math.random()*100))%100;
list.insert(i, temp);
System.out.print(temp +" ");
}
list.delete(4);
System.out.println(" "+"after deleting the 5th number:");
for(int i =0; i <list.size; i++){
System.out.print(list.locate(i).data.toString()+" ");
}
}
}
输出结果:
9588231885799228418
after deleting the 5th number:
95882315799228418