Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65

## Linked List – insert element at position

In this post we’ll implement another algorithm for Linked List – insert element at position. The algorithm works in linear time in the worst case.

## Linked List insert element at position

We base our Linked List implementation on Node class, we’ve defined in the previous post.

```public void insert(int position, T value) {
Node<T> newNode = new Node<>(value);

// insert as the new head?
if (position == 0) {
// The 1st case.
} else {
// The 2nd case.
// find position just before the expected one:
while (--position > 0) {
node = node.next;
}
// insert the new node:
newNode.next = node.next;
node.next = newNode;
}
}
```

## How it works

The insertion algorithm has to support two cases.

The first case is inserting the element at the head of the list – be it an empty list or just at index 0 in an existing list. To handle this correctly we have to be sure to not overwrite the old head with the new one.
The second case is inserting the element at a position other than the head of list. To do that we have to find the node just before the expected one and insert the new node there.
Because in the second case we may need to traverse whole Linked List, the worst time complexity of the algorithm is linear – O(n).
Both cases are handled in the above code.

## JUnit tests

As always, to check that the algorithms actually works and inserts given elements at specified positions, we’ll write unit tests:

```package com.farenda.tutorials.algorithms.lists;

import org.junit.Test;

import static org.junit.Assert.*;

@Test
public void shouldInsertAtSpecifiedPosition() {
list.insert(0, 2);
assertEquals(1, list.size());
list.printContent();

list.insert(1, 3);
assertEquals(2, list.size());
list.printContent();

list.insert(0, 1);
assertEquals(3, list.size());
list.printContent();
}
}
```

When we run the tests, they will produce:

```[2]
[2,3]
[1,2,3]
```

## References:

Share with the World!