Skip to content

toString method for a linkedList

I am getting strange output for my toString in my linkedList class.

I cannot use any methods, only String concat. So limited in how to approach this.

Here is the code:

@Override
public String toString() {
if (head == null) {
return "";
}
String result = "";
Node curr = head;

while (curr.next != null) {
curr = curr.next;
result += curr.data + ", ";
}
return result;
}

I wrote a JUnit test that:

assetsEquals(
"8,6,7,5,3,0,9, " + "9,0,3,5,7,6,8", dataTest.noOrderList().toString());

and that noOrderList().toString() comes from:

public static noOrderList<Integer> noOrderList() {
return makeListInNoOrder(new Integer[]{ 8, 6, 7, 5, 3, 0, 9, 9, 0, 3, 5, 7, 6, 8});

When I run the test I get:

expected:<... 3, 0, 9, 9, 0, 3[]> but was: <... 3, 0, 9, 9, 0, 3[, ]>

Was is the cause of this , in the [, ] how do I eliminate that comma?

Thank you

Answer

You always append the ", " string to the result.

  • So, for the first element, you append "9, ".
  • For the second, it’s "0, "
  • and so on…
  • Finally, you add "3, " for the last.

Instead, you should append the ", " only if the next element is not null.

E.g.:

while (curr.next != null) {
curr = curr.next;
    result += curr.data;
    if (curr.next != null)
        result += ", ";
}

to save some comparisons, you should emit the ", " before the element, and emit the first element before the loop:

//don't print head, since that seems to be empty in your implementation.
//also make sure head does not reference `null` by accident...
if (curr.next == null)
    return result;
curr = curr.next;

//1st element after `head`
result += curr.data;

while (curr.next != null) {
    curr = curr.next;
    result += ", " + curr.data;
}

I also noticed you never put the head element into the result. Is it empty, or is that a mistake?