双向链表(java版)
上一篇 /
下一篇 2008-04-30 08:38:05
/ 个人分类:数据结构
1. Dnode
|
package zhangy;
public class Dnode {
public Object data;
public Dnode next;
public Dnode previous;
Dnode()
{
data=null;
next=null;
previous=null;
}
Dnode(Object o)
{
this.data=o;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Dnode getNext() {
return next;
}
public void setNext(Dnode next) {
this.next = next;
}
public Dnode getPrevious() {
return previous;
}
public void setPrevious(Dnode previous) {
this.previous = previous;
}
} |
1
2.DLinkList
|
package zhangy;
public class DLinkList implements List{
private Dnode head;
private Dnode tail;
private int size;
DLinkList()
{
head=tail=new Dnode();
size=0;
}
public void insertElement(int i,Object o) throws Exception
{
if(i<0||i>size+1)
{
throw new Exception("位置错误");
}
Dnode newnode=new Dnode();
if(tail==head)
{
newnode.setPrevious(head);
head.setNext(newnode);
tail=newnode;
}
else if(i==size+1)
{
newnode.setPrevious(tail);
tail.setNext(newnode);
tail=newnode;
}
else{
Dnode temp=head;
for(int j=1;j<=i;j++)
{
temp=temp.getNext();
}
newnode.setNext(temp);
newnode.setPrevious(temp.getPrevious());
temp.getPrevious().setNext(newnode);
temp.setPrevious(newnode);
}
size++;
}
public void deleteElement(int i) throws Exception
{
if(i<=0||i>size)
{
throw new Exception("位置错误");
}
if(size==1)
{
head.setNext(null);
tail=head;
}
else if(size==i)
{
tail.getPrevious().setNext(null);
tail=tail.getPrevious();
}
else
{
Dnode temp=head;
for(int j=1;j<=i;j++)
{
temp=temp.getNext();
}
temp.getNext().setPrevious(temp.getPrevious());
temp.getPrevious().setNext(temp.getNext());
}
size--;
}
public Object getElement(int i) throws Exception
{
if(i<=0||i>size)
{
throw new Exception("位置错误");
}
Dnode temp=head;
for(int j=1;j<=i;j++)
{
temp=temp.getNext();
}
return temp;
}
public int getSize()
{
return size;
}
public boolean isEmpty()
{
return (size==0);
}
} |
导入论坛
引用链接
收藏
分享给好友
推荐到圈子
管理
举报
TAG: