Reputation: 109
I am trying to write a method to concatenate a specified string called lstring to the end of this lstring. My problem right now is that my required return type is different from the type I use to perform the recursive function.
This is a linked list class (LString) that calls and references another class (Node). We are to specifically use this method header: public LString concat(LString lstr)
How do I correct my concatenation method so that I can accept the required LString type?
This is the method I tried:
public LString concat(LString lstr){
if(front == null){
return this;
}
LString lstr2 = new LString();
return front.toString() + concat(front.getNext());
}
Here is the relevant code for my classes:
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;
}
}
And my Node class (singly linked nodes):
public class Node{
public char data;
public Node next;
//constructors from page 956
public Node()
{
this('\0',null); //'\0' is null char for java
}
public Node(char initialData, Node initialNext)
{
data = initialData;
next = initialNext;
}
If I can provide anymore information to help clarify the question let me know.
Also from http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim() Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string. Examples: "cares".concat("s") returns "caress" "to".concat("get").concat("her") returns "together"
Upvotes: 0
Views: 3261
Reputation: 1857
The line return current.data + concat(current.next) + this;
seems to be where your code is failing, yet you didn't provide any code that includes that line. Hence, it is hard to tell what exactly is wrong there. But, by looking only at that line: you are trying to return not a single type element, but a collection of different onces.
current.data is char
concat is LString
and this
is whatever object you are using at that time.
And you are trying to add them up together.
Upvotes: 1