对于家庭作业,我应该使用节点和指针创建一个循环链接列表。
这是我的节点类
class Node implements Serializable {
public String theName; //the wrapped name
public Node next; //the next node in the sequence
public Node prev; //the previous node in the sequence
public Node(Node p, String s, Node n){
prev = p;
theName = s;
next = n;
}
}
我试图在列表的前面插入字符串(名称),然后使用遍历方法将它们打印出来。
到目前为止,这些是我的遍历和插入方法......
public class ListImpl /*implements List*/ {
Node list;
public ListImpl() {
list = new Node(list, null, list);
}
public void insert(String s) {
if (list == null) {
list = new Node(list, s, list);
} else {
list = new Node(list.prev, s, list);
list.next.prev = list;
list.next.next = list;
}
}
public void traverse(ASCIIDisplayer out) {
Node p = new Node(null, null, null);
p = list;
if (list != null) {
while(true) {
out.writeString(p.theName);
p = p.next;
}
} else {
throw new EmptyListException();
}
}
}
我知道我的遍历方法将是一个连续循环,我必须弄清楚如何让它在回到列表开头时停止,但这不是我的问题。
我相信我的问题在于插入方法,因为当我运行此代码(主要)时,我的输出不符合预期:
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ASCIIDisplayer a = new ASCIIDisplayer();
ListImpl List;
List = new ListImpl();
List.insert("Steve");
List.insert("Kuba");
List.insert("Taylor");
List.insert("Jane");
List.traverse(a);
}
}
我得到的输出是:Taylor Jane Taylor Jane Taylor Jane Taylor Jane...重复。
我预计输出为:Steve Kuba Taylor Jane Steve Kuba Taylor Jane...重复。
这就是为什么我认为问题出在插入方法中,我的指针一定指向错误的节点,但我就是不知道我做错了什么。
很抱歉问了这么长的问题,希望有足够的信息可以帮助我! 提前致谢!
最佳答案
替换这个:
list = new Node(list.prev, s, list);
list.next.prev = list;
list.next.next = list;
这样:
Node tmpList = new Node(list.prev, s, list);
list.next.prev = tmpList;
list.prev.next = tmpList;
list = tmpList;
至于确定何时重复节点,您可以通过保存第一个节点并比较它是否与下一个节点相同来实现,当发生这种情况时,您就到达了列表的末尾。
此外,当您插入第一个节点时,您将执行以下操作:
if (list == null) {
list = new Node(list, s, list);
在这种情况下,传递给构造函数的两个 list
参数都是 null
,您应该通过创建一个仅采用 的新构造函数来解决此问题>String
值,然后引用自身或通过手动设置 prev
和 next
。
这是构造函数解决方案:
class Node implements Serializable {
public String theName; //the wrapped name
public Node next; //the next node in the sequence
public Node prev; //the previous node in the sequence
public Node(Node p, String s, Node n){
prev = p;
theName = s;
next = n;
}
public Node(String s){
prev = this;
theName = s;
next = this;
}}
关于java - java中双向循环链表的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5445418/