Skip to content
Advertisement

How do I insert an Item at a certain Index in a Linked 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 to create 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 execute this method nothing happens. The item that I try to add to a specific index never gets added. Does someone know what I did wrong? and How to fix it?

JavaScript

Advertisement

Answer

There are a few issues, but you are most of the way there, you simply need to move the if statement if (index == i) {Node newItem... } inside of your ‘for’ loop like this:

JavaScript

Note that your code had an error, which has been fixed by checking that the next node is not null.

We can see the updated method works by inserting 999 after index 2:

JavaScript

If you want the item to be inserted at index 2 instead, then adjust the order and put the if statement before prev = temp;

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