Skip to content
Advertisement

Java – Remove Items From Linked List

I have the following java class with constructor and getters and setters.

JavaScript

And also another class, wagon which is used by the train class.

JavaScript

I initialise a new train like so:

JavaScript

I want to write a method that takes a train as an input, iterates through the wagons, if the cargo attribute matches a supplied string, the wagon is deleted. I have written this method which creates a new linkedlist and adds the trains wagons to it. It then iterates through this list and removes any matches. I am trying to iterate again through the modified list and use the setFreight method to update the actual train object.

JavaScript

I think I’m close, but don’t know how to write a method that will produce an output like:

trainC2.setFreight(new Wagon("wheat", 400, new Wagon("wheat", 300, new Wagon("maize", 280))));

Or maybe there’s a better way altogether?

Advertisement

Answer

You are not iterating over Wagons because when you call wag8.add(train.getFreight()), now your list has only one Wagon. My suggestion is to write a method named ‘hasNext()’ in your Wagon class so that you can know if there is another Wagon connected to the current wagon. Something like this:

JavaScript

You seem to want to delete some wagons from the middle of the train. Let’s say you want to delete the third wagon. For that, you can change the ‘next’ reference of the second wagon to point to the fourth wagon. Then you have no third wagon!

JavaScript

Some parts of code are ambiguous. So don’t hesitate to ask how does it work.

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