Skip to content
Advertisement

How can I insert an Item at the end of the List?

I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.

  • Use an inner class for the Node.
  • Include the methods below.
  • Write a tester to enable you to test all of the methods with whatever data you want in any order.

I have a method called “public void insertAt(int index, int item)”. This method is meant to “Insert an item at position index, where index is passed to the method” I have my code for this method down below. When I insert an Item at an Index it works unless it’s the last item in the list. When I try to insert an item at the end of the list it replaces the last item and the item that was there before is erased when It shouldn’t. For example, If I had a list: “[9, 8, 15, 7, 5, 15, 19, 6, 19, 2]” and I want to insert the number “90” and the last index it should look like [9, 8, 15, 7, 5, 15, 19, 6, 19, 90, 2] but instead I get [9, 8, 15, 7, 5, 15, 19, 6, 19, 90]. How can I fix this in my code so if I was to insert an item at the tail it would move the Item I want inserted to be placed before the tail?

JavaScript

Advertisement

Answer

You have an error in this line:

JavaScript

Right there, temp is your last element, be it 2. Your new element ( 90) will only have temp assigned, it temp has a pointer to the next element (temp.nextNode != null) Because temp has no next element, nextNode won’t be assigned at all. In fact, you can omit this check at all cause if temp was null , you would only assign null to the nextNode of the newItem which would be fine.

Also, make sure to handle other issues in your implementation, such as adding the element at index 0. At the moment, in the beginning you set Node prev = null; and then in the first iteration of the loop prev is null and you would end up with the NPE whenever you try to add the element at index 0.

To fix this, you need to change this section:

JavaScript

into

JavaScript

Writing good unit tests may help you with the robust implementation and will help you solve this kind of issues much quicker. Check out this question to see how to write unit tests in java.

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