Note that there are some explanatory texts on larger screens.

plurals
  1. PODeleting first node in linked list after the rest has be deleted
    primarykey
    data
    text
    <p>I have to implement a linked list in the form of a bag. Usually, bags don't have remove but in this case I need one.</p> <p>When I run my test client, and I call remove, all instances of that item in my linked list is deleted, except for the very first value. </p> <p>So essentially my output looks like this:</p> <pre><code>removed all 9s: 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1 4 4 3 3 2 2 1 1 removed all 3s: 4 4 4 4 4 2 2 2 2 2 1 1 1 1 1 4 4 2 2 1 1 removed all 1s: 4 4 4 4 4 2 2 2 2 2 4 4 2 2 removed all 4s: 4 2 2 2 2 2 2 2 removed all 2s: 4 </code></pre> <p>Here is my code:</p> <pre><code>public void remove (int item) { // TODO Node previous = null; Node current = first; if (first == null) // list is empty do nothing { } else if (first.item == item) // item occurs in first node { //previous = first; first = first.next; } // skip around first node else { // find the node before item for (Node p = first.next, q = first; p != null; q = p, p = q.next) { if (p.item == item) { q.next = p.next; //p.next = q.next; //return; } } } while (current != null) { if(current.item == item) { current = current.next; if (previous == null) previous = current; else previous.next = current; } else { previous = current; current = current.next; } } //end while //return; } </code></pre> <p>Here is the test client code:</p> <pre><code>b1.remove(9); print ("removed all 9s", b1); // does nothing b1.remove(3); print ("removed all 3s", b1); b1.remove(1); print ("removed all 1s", b1); b1.remove(4); print ("removed all 4s", b1); b1.remove(2); print ("removed all 2s", b1); // should be empty </code></pre> <p>Can someone help me figure out why that 4 remains after it was supposed to have been deleted?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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