永发信息网

java中LinkedList的问题

答案:2  悬赏:0  手机版
解决时间 2021-06-02 04:13

public class Test2{
public static void main(String[] args){
LinkedList1 ll=new LinkedList1();
for(int i=0;i<25;i++){
ll.add(new Cat(i));
}
while(ll.hasNext()){
System.out.println(ll.next());
}
while(ll.hasNext()){
System.out.println(ll.next());
}
}
}

class LinkedList1{
private Node n;
private Node nn;
private Node head;
private Node tell;
private int index;
private int currentIndex=0;
private Object o;
public void add(Object o){
n=new Node(o,null);
if(head==null){
head=n;
tell=n;
}
tell.setNode(n);
tell=n;
index++;
}
public int size(){
return index;
}
public boolean hasNext(){
if(currentIndex>=index){
currentIndex=0;
return false;

}
else{
return true;
}
}
public Object next(){
o=head.getObject();
head=head.getNode();
currentIndex++;
return o;
}
}

class Node{
private Object o;
private Node n;
Node(Object o,Node n){
this.o=o;
this.n=n;
}
public Object getObject(){
return o;
}
public Node getNode(){
return n;
}
public void setObject(Object o){
this.o=o;
}
public void setNode(Node n){
this.n=n;
}
}

class Cat{
private int id;
Cat(int id){
this.id=id;
}
public int getId(){
return id;
}
public String toString(){
return "Cat id "+id+" is couStruct";
}
}

今天写了个LinkedList类 但是只能遍历一遍,第二遍就会出错。。

我知道我在遍历的时候改变了原来的数据 所有才有这样的结果

请教各位高手, 有没有好一点的方法 实现遍历呢。

最佳答案
你在链表类里另设一个Node it作遍历用就行了
不要在遍历的时候改变head本身,比如

public Object next(){
if ( it == null ) {
it = head;
o = it;
} else {
o =it.getObject();
it=it.getNode();
}
currentIndex++;

return o;
}
全部回答

百度迭代器的原理

我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
蜘蛛在制新网时,它的第一丝是怎么拉到对岸去
热血英豪雪妖用什么装备好(我比喜欢陀螺)
我开着超级QQ,为什么今天没有算活跃天数
求nokiaN86深圳华强北水货价?
客吧火锅鸡,夜色静吧地址在什么地方,想过去
虎年宝宝几月出生好
最近大家都开心么?
胡子小鸡下载
有全本小说的推荐一下
万里果菜超市这个地址在什么地方,我要处理点
华谊股市行情
大门跟次卧室的门相对,行不行?
关于qq牧场我昨天已经开通了,怎么今天就又进
我是1990年农历8月21日下午5点多出生的,我想
广东四区骨戒大概值多少
推荐资讯
男人为什么叫男人?
求华南理工2011年研招结构力学的考纲……
属羊的白羊座和属猴的摩蝎座配吗?
为什么QQ游戏只能小屏 大屏不行
李宁运动品牌
求塞班的手机证书
武林三国里怎么样把自己分城的士兵派到自己的
上海徐汇区自考094助学点在哪
飞车怎么查询自己买过的东西
电影人蛇大战,有几部?
谁知道有没这本书《东妮与冷珊》小说
父亲买了一套房,是父亲付的首付,目前一直由
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?