Skip to content
Advertisement

Removing values from a custom LinkedList class

This custom class mimics the functionality of Java’s LinkedList Class except it only takes integers and obviously lacks most of the functionality. For this one method, removeAll(), I am to go through each node for the list and remove all nodes with that value. My problem is that when the first node in the list contains the value to be removed, it then ignores all subsequent nodes that also contain that value. What seems to be the problem? Am I removing the front node the wrong way? For example, [1]->[1]->[1] should return an empty list, but it leaves the front node and I get [1]

edit: it seems to fail to remove the second node instead of the first.

This is the class (Stores ListNodes as a list):

JavaScript

Here is the ListNode class (responsible for a single “node”):

JavaScript

Advertisement

Answer

The [1] element that actually stays in the list is the second element which becomes the front element in your code:

JavaScript

After that you just iterate over the list and remove the matching elements. Replacing the problematic code with this should do the work:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement