Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem is with the <code>add</code> method: it appears that the method adds the item as the number two in the list, rather than adding it to its end. This does not apply to the initial entry, because the head and the tail are the same for it.</p> <p>To fix this problem, keep the <code>Node last</code> element in the <code>CircularList</code>, and do the insertion at the <code>last</code>, not at the <code>first</code> element. This makes deletion of the last element a little harder to manage, but the speedup that you gain is worth it.</p> <p>If you would like to surprise your teacher, you can use a "magic trick":</p> <pre><code>public void add(int value) { if(first == null) { first = new Node(value, null); first.setNext(first); } else { // Remember the current first Node oldFirst = first; // Make a copy of the first node the "new first" first = new Node(first.getValue(), first.getNext()); // Copy the new value into the "old first", // and make its next point to the "new first" oldFirst.setValue(value); oldFirst.setNext(first); } System.out.println("Added: " + value); size++; } </code></pre> <p>Make sure that you fully understand this trick. Draw it on a piece of paper to understand it better. Your teacher may ask you about this, because it's not very common.</p> <p>As far as the printing goes, do not use <code>+=</code>, use <code>StringBuilder</code> instead. You can also avoid the counter by observing that your printing should end when the <code>curr</code> reaches <code>first</code> again:</p> <pre><code>public String print() { StringBuilder str = new StringBuilder(); Node curr = first; while (true) { str.append(curr.getData()); curr = curr.getNext(); if (curr == first) break; } return str.toString(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload