Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove all occurrences of item from a Linked List
    primarykey
    data
    text
    <p>I've been working on this lab assignment for a few hours and can't understand why this code is not working. The question is to add the method <code>int removeEvery(T item)</code> that removes all occurrences of item and returns the number of removed items to a link list class that implements a link list interface.</p> <p>This is my code: It removes some occurrences of the item, but not all of them. </p> <pre><code>public int removeEvery(T item){ int index = 0; Node currentNode = firstNode; for(int i = 1; i &lt;= numberOfEntries; i++) { System.out.println(currentNode.getData()); if (item.equals(currentNode.getData())){ index++; remove(i);} else{ currentNode = currentNode.getNextNode();} } if(index != 0) return index; return -1; } </code></pre> <p>Here is the remove method that was included in the LinkList class:</p> <pre><code>public T remove(int givenPosition) { T result = null; // return value if ((givenPosition &gt;= 1) &amp;&amp; (givenPosition &lt;= numberOfEntries)) { assert !isEmpty(); if (givenPosition == 1) // case 1: remove first entry { result = firstNode.getData(); // save entry to be removed firstNode = firstNode.getNextNode(); if (numberOfEntries == 1) lastNode = null; // solitary entry was removed } else // case 2: givenPosition &gt; 1 { Node nodeBefore = getNodeAt(givenPosition - 1); Node nodeToRemove = nodeBefore.getNextNode(); Node nodeAfter = nodeToRemove.getNextNode(); nodeBefore.setNextNode(nodeAfter); // disconnect the node to be removed result = nodeToRemove.getData(); // save entry to be removed if (givenPosition == numberOfEntries) lastNode = nodeBefore; // last node was removed } // end if numberOfEntries--; } // end if return result; // return removed entry, or // null if operation fails } // end remove </code></pre>
    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.
    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