数据结构 循环单链表

发布网友

我来回答

1个回答

热心网友

package e.cquptzx.List;
publicinterface List
{
publicvoid insert(int i ,Object obj) throws Exception; //插入
public Object delete(int i ) throws Exception; //删除
public Object getData(int i ) throws Exception; //获取i元素
publicint size(); //表数据总数
publicboolean isEmpty(); //是否为空

}
循环单链表实现:
package e.cquptzx.List;

publicclass LoopLinkList implements List {
Node head;
Node current;
intsize;

LoopLinkList()
{
head = current = new Node(null);
head.next = head;
size =0;
}
/**
* 定位成员函数index(int i)的实现
* 循环从头开始查找,循环的条件是:1.定位完成j==i;2.链表查找结束了.
* @param i
* @throws Exception 当参数i错误时,抛出异常.
*/
publicvoid index(int i )throws Exception
{
if(i<-1 || i >size-1)
{
thrownew Exception("i error in INDEX.");
}
if(i == -1) return;
current = head.next;
int j = 0;
while(current!=head && j<i)
{
current = current.next;
j++;
}
}
/**
* 插入节点算法:
* 1.调用index(i-1),让成员变量current指向第i-1个节点.
* 2.以obj,current.next为参数创建新的节点.
* 3.更改current指向,改为下一个节点.
* 4.表元素总数加1.
*/
publicvoid insert(int i, Object obj) throws Exception {
if(i<0 || i>size)
{
thrownew Exception ("i error in INSERT.");
}
index(i-1);
current.setNext(new Node(obj,current.next));
size++;
}

/**
* 删除节点算法:
* 1.调用index(i-1),让成员变量current指向第i-1个节点.
* 2.把第i个节点脱链:让第i-1个节点的next域等于第i个节点的next域.
* 3.数据元素总数size减1.
*/
public Object delete(int i) throws Exception {
if(size == 0)
{
thrownew Exception ("Link Blank in DELETE.");
}
if(i<0 || i>size-1)
{
thrownew Exception ("i error in DELETE.");
}
index(i-1);
Object obj = current.next.getElement();
current.setNext(current.next.next);
size--;
return obj;
}
/**
* 获取指定的元素
* 1.调用index(i),让成员变量current指向第i个节点.
* 2.返回该节点的数据域的值.
*/
@Override
public Object getData(int i) throws Exception {
// TODO Auto-generated method stub
if(i<-1 || i>size-1)
{
thrownew Exception ("i error in getData.");
}
index(i);
returncurrent.getElement();
}

@Override
publicint size() {
// TODO Auto-generated method stub
returnsize;
}

@Override
publicboolean isEmpty() {
// TODO Auto-generated method stub
returnsize ==0;
}

}
循环单链表输出测试:
package e.cquptzx.List;

publicclass LoopLinkListTest
{
publicstaticvoid main(String agrs[])
{
LoopLinkList lplklt = new LoopLinkList();
int n = 10;
try
{
for(int i = 0;i<n;i++)
{
lplklt.insert(i, new Integer(i+1));
}
lplklt.delete(4);
for(int i = 0;i<lplklt.size;i++)
{
System.out.print(lplklt.getData(i)+"...end ");
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

输出结果:

分类: 数据结构-java标签: 循环单链表绿色通道: 好文要顶 关注我 收藏该文与我联系 淅沥枫
关注 - 6
粉丝 - 9 +加关注 1 0 (请您对文章做出评价) « 上一篇:单链表-数据结构-java实现
» 下一篇:双向链表-数据结构-java实现
posted @ 2012-10-06 17:59 淅沥枫 阅读(951) 评论(0) 编辑 收藏追问用c++实现

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com