我正在尝试编写一个方法,将一个名为lstring的指定字符串连接到此lstring末尾。我现在的问题是,我需要的返回类型与我用来执行递归函数的类型不同。
这是一个链表类(LString),它调用并引用另一个类(Node)。我们要特别使用这个方法头:public LString concat(LString lstr)
如何更正连接方法,以便接受所需的LString类型
这是我尝试过的方法:
public LString concat(LString lstr){
if(front == null){
return this;
}
LString lstr2 = new LString();
return front.toString() + concat(front.getNext());
}
以下是我的类的相关代码:
public class LString{
private Node front = null; //first val in list
private Node back; //last val in list
private int size = 0;
private int i;
public LString(){
//construct empty list
Node LString = new Node();
front = null;
}
public String toString(){
if(front == null){
return "[]";
} else {
String result = "[" + front.data;
Node current = front.next;
while(current != null){
result += current.data; //might need to add ", page 967
current = current.next;
}
result += "]";
return result;
}
}
我的Node类(单链接节点):
public class Node{
public char data;
public Node next;
//constructors from page 956
public Node()
{
this(' ',null); //' ' is null char for java
}
public Node(char initialData, Node initialNext)
{
data = initialData;
next = initialNext;
}
如果我能提供更多的信息来帮助澄清这个问题,请告诉我。
也来自http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim()将指定的字符串连接到此字符串的末尾。如果参数字符串的长度为0,则返回此string对象。否则,将创建一个新的String对象,表示一个字符序列,该字符序列是此String对象所表示的字符序列和参数字符串所表示的字符串序列的串联。示例:concat("s")返回"爱抚"to".concat("get").concot("her")返回"together"
return current.data + concat(current.next) + this;
行似乎是代码失败的地方,但您没有提供任何包含该行的代码。因此,很难判断到底哪里出了问题。但是,只看这一行:您试图返回的不是单个类型元素,而是不同once的集合。current.data为charconcat是LStringCCD_ 3是您当时使用的任何对象。
你正试图把它们加在一起。