-2

The toString method returns a String containing the items of all the nodes in the list separated by commas. The current version will not work correctly if the list is circular,I need to Fix the method so that it will work correctly for both normal and circular lists. but im struggling with my current code

public String toString(){
    String str = "";
    Node current = head;
    while(current != null){
        str = str + current.getItem();
        current = current.next();
        if (current != null){
            str = str + ", ";
        }
    }
    return str;
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190

1 Answers1

1

You are almost there: simply check that current is not head after calling current.next():

current = current.next();
if (current == head) {
    break;
}

Breaking out of the loop has to be done before appending ", " to str.

Note: Composing strings with += is suboptimal, especially in a loop (why?). Consider switching to StringBuilder (example).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523