Java 循环双链接列表到字符串不工作
我有一个toString和一个helper方法来打印我创建的循环链表类的结果。就是这样:Java 循环双链接列表到字符串不工作,java,tostring,doubly-linked-list,Java,Tostring,Doubly Linked List,我有一个toString和一个helper方法来打印我创建的循环链表类的结果。就是这样: /** * Returns a String version of this. * * @return A String description of this. */ public String toString(){ String string = ""; DoubleNode<E> current = this.head; string
/**
* Returns a String version of this.
*
* @return A String description of this.
*/
public String toString(){
String string = "";
DoubleNode<E> current = this.head;
string += stringHelper(this.head);
return string;
}
//Helps the full to string method
private String stringHelper(DoubleNode<E> node){
String string = "";
if(node == null){
return string;
}
System.out.println("Node value: " + node.getValue());
node = node.getNextLink();
if(node == this.head){
string += node.getValue();
return string;
}
else{
string += node.getValue();
return (stringHelper(node.getNextLink()) + ", " + string);
}
}
/**
*返回此文件的字符串版本。
*
*@返回此的字符串描述。
*/
公共字符串toString(){
字符串=”;
双节点电流=这个头;
string+=stringHelper(this.head);
返回字符串;
}
//帮助完整的字符串转换方法
私有字符串stringHelper(双节点){
字符串=”;
if(node==null){
返回字符串;
}
System.out.println(“节点值:+Node.getValue());
node=node.getNextLink();
if(node==this.head){
string+=node.getValue();
返回字符串;
}
否则{
string+=node.getValue();
返回(stringHelper(node.getNextLink())+“,”+字符串);
}
}
然而,它似乎不起作用。我有一个测试用例,它应该打印出40,10,2,但它只打印出40,10。有人能帮我吗?我相信你应该用
stringHelper(node.getNextLink())
替换递归调用stringHelper(node)
,就像你在stringHelper()
方法中调用node.getNextLink()
两次一样,这是不对的。我想出来了。很抱歉发布此消息,因为我应该自己完成此操作。我最后做了:
/**
* Returns a String version of this.
*
* @return A String description of this.
*/
public String toString(){
String string = "";
DoubleNode<E> current = this.head;
string += stringHelper(this.head);
return string;
}
//Helps the full to string method
private String stringHelper(DoubleNode<E> node){
String string = "";
if(node == null){
return string;
}
string+= node.getValue();
string+= ", ";
node = node.getNextLink();
if(node == this.head){
return string;
}
else{
string += node.getValue();
return (string + ", " + stringHelper(node.getNextLink()));
}
}
/**
*返回此文件的字符串版本。
*
*@返回此的字符串描述。
*/
公共字符串toString(){
字符串=”;
双节点电流=这个头;
string+=stringHelper(this.head);
返回字符串;
}
//帮助完整的字符串转换方法
私有字符串stringHelper(双节点){
字符串=”;
if(node==null){
返回字符串;
}
string+=node.getValue();
字符串+=“,”;
node=node.getNextLink();
if(node==this.head){
返回字符串;
}
否则{
string+=node.getValue();
返回(字符串+”,“+stringHelper(node.getNextLink());
}
}
当你用纸和笔追踪它的执行情况时,你发现了什么?或者当你使用调试器进行调试时?出于某种原因,print语句打印出40,然后打印出2,但我不知道为什么会这样。我没有任何调试经验。当我像你说的那样替换它时,它只打印出第一个元素,因为不再有任何遍历。如果没有整个类代码,很难给出正确的答案。但无论如何,您的问题是调用node.getNextLink()
两次