循环双向链表 toString 不起作用
Circular Doubly Linked List toString not working
我有一个带有辅助方法的 toString 来打印我创建的循环链表 class 的结果。就是这样:
/**
* 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);
}
}
但是,它似乎不起作用。我有一个测试用例,它应该打印出 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 来打印我创建的循环链表 class 的结果。就是这样:
/**
* 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);
}
}
但是,它似乎不起作用。我有一个测试用例,它应该打印出 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()));
}
}