Skip to content
Advertisement

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:

JavaScript

I wrote a JUnit test that:

JavaScript

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

JavaScript

When I run the test I get:

JavaScript

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

Thank you

Advertisement

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.:

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement