Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There's a lot going on in your code, here's some advice for some of it:</p> <ol> <li><p>In your Node class: Java naming conventions: the same way that setters should be prefixed with "set," getters should be prefixed with "get:" <code>nextItem()</code> should really be <code>getNextItem()</code>.</p></li> <li><p>Also in your Node class: as far as I know, the "next value" field of a node of a linked list is usually a reference to the next Node in the list, and should therefore be of type <code>Node</code>, not just any Object. It should work the way you have it, but using explicit typing is a lot safer. (Please correct me if using "Object" is indeed a common way to construct the next node of a linked list.)</p></li> <li><p>In the first case of <code>remove()</code>, when removing the head: you're looping through the list to reach the last value, presumably to reset its "next value" to the new head, but you're not actually doing it. You want something like this:</p> <pre><code>if (item == head) { head = head.nextItem(); for(int i = 0; i &lt; arrSize-1; i++){ cur = cur.nextItem(); } } cur.setNextItem(head); </code></pre> <p>I'm not sure what you hope to accomplish with the second loop.</p></li> <li><p>In the second case of <code>remove()</code>: I'm not sure what you're trying to do with the second <code>while</code> loop - reset all the links in the whole list? The whole point of a linked list is to make that unnecessary. Deleting a node in a linked list does not actually get rid of the object (so you don't have to set <code>item</code> to <code>null</code>). Rather, you simply "go around" the unwanted object and "ignore" it, effectively removing it from the list, as in:</p></li> </ol> <p>Original list:</p> <pre><code>[ Value: A; Next: B ] --&gt; [ Value: B; Next: C ] --&gt; [ Value C; Next: D ] ... </code></pre> <p>After deleting node B:</p> <pre><code> [ Value: A; Next: C ] --&gt; [Value C; Next: D ] ... </code></pre> <p><code>[ Value: B; Next: C ]</code> still exists in memory, but nothing is pointing to it, so it will be removed in the next garbage collection cycle.</p> <p>To implelement: As you walk the list, keep a reference to the previous node that you visited. Then, once you find the item you're looking for (using correct comparison, as Thomas noted), you can simply set <code>prev.setNextItem(cur.nextItem());</code> (caveat: untested code):</p> <pre><code> Node prev = head; Node cur; while ((cur = prev.nextItem()) != head) { if (cur.equals(item)) { prev.setNextItem(cur.getNextItem()); return true; } } </code></pre> <p>I hope these tips help you along the correct path.</p>
 

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