所以我正在学习Java,我想实现一个单链表,但是当我尝试打印它时,它进入一个无限循环,只打印第一个元素,好像temp
没有不能重新分配。这有什么不对?
public class Cons
{
public int stuff;
public Cons next;
public Cons(int i)
{
this(i, null);
}
public void show()
{
Cons temp = this;
while(temp != null)
{
System.out.println(temp.stuff);
temp = temp.next;
}
}
public void push(int i)
{
stuff = i;
next = this;
}
public static void main(String[] args)
{
Cons head = new Cons(2);
head.push(3);
head.push(12);
head.show();
}
}
答案 0 :(得分:3)
在这个块中:
public void push(int i)
{
stuff = i;
next = this;
}
您正在将节点的next
分配给自己。
请改为尝试:
public void push(int i)
{
next = new Cons(i);
}
那将删除自循环,但是你仍然会有记住尾部位置的问题。我将把它留作练习,因为这是一项功课。
注释中指出的另一个问题是你的代码不应该按原样编译,因为你试图调用一个不存在的构造函数。
如果你想调用this(i, null)
,你需要一个以(int, Cons)
作为其句子的构造函数。
答案 1 :(得分:0)
尝试创建in wikipedia所示的代码。您需要Container来保存节点,Node需要表示列表中的单个节点
答案 2 :(得分:0)
我认为
next = this
错误,您应该创建一个新条目
next = new Cons(stuff);
stuff = i;
否则下一个条目将指向当前条目! 请注意,如果以这种方式执行,则元素的顺序会颠倒过来。
答案 3 :(得分:0)
public void push(int i)
{
stuff = i;
next = this; //here's the problem.
}
您需要以下内容:
public void push(int i)
{
Cons newnext = new Cons(i)
tail.next = newnext;
tail = newnext;
}
当然,您需要引用链接列表的尾部某处。