Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Linked List – remove element

As many other algorithms in Linked Listremove element from given position runs in linear time. Here we are going to implement it to better understand how it works.

In previous posts we’ve implemented add, count, print contents, and insert methods for a Linked List. Now we will implement removal of element from selected position.

Linked List – remove element at position

As previously, we base our Linked List implementation on Node class, we’ve defined in the first post.

public void remove(int position) {
    Node<T> prev = null, node = head;
    // Find node to remove:
    while (position > 0 && node != null) {
        prev = node;
        node =;
    // If exists, unpin it from the list:
    if (node != null) {
        if (prev == null) {
            // Removed 1st, so change the head:
            head =;
        } else {
            // Just connect prev with next:

How it works

The algorithm consists of two parts. First, we have to find the node we want to remove and remember its predecessor, so that we could connect it to the next node.
In the second part, if the node was found, we have to handle two cases. If we remove a node from the first position, it means we are removing the head, therefore we have to promote the next node to be the new head. In every other case we just need to connect previous node with the node after the removed one.


It’s pretty clear that in the worst case – removal of element from the last position – we have to iterate through whole Linked List. Thus the algorithm runs in linear timeO(n).

Unit Tests

Let’s write a simple unit tests to see how the algorithm works:

package com.farenda.tutorials.algorithms.lists;

import org.junit.Test;

import static org.junit.Assert.*;

public class LinkedListTest {

    private LinkedList<Integer> list = new LinkedList<>();

    public void shouldRemoveElements() {

        assertEquals(3, list.size());

        assertEquals(2, list.size());

        assertEquals(1, list.size());

        assertEquals(0, list.size());


The above code produces the following output:

Share with the World!