Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java LinkedList exercises with checked solutions

Last updated: 29 Sept 20264 min read
tutorial
By AITrove Editorial

LinkedList exercises should distinguish value removal, endpoint behavior, and iterator-safe edits.

Requirements

  • Remove only the first matching retry code, without treating it as an index.
  • Remove completed jobs during a traversal.
  • Verify that polling an empty queue returns null.

Reference solution

Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListChecks {
    public static void main(String[] args) {
        LinkedList<Integer> retries = new LinkedList<>(Arrays.asList(2, 5, 2));
        boolean removed = retries.remove(Integer.valueOf(2));
        if (!removed || !retries.equals(Arrays.asList(5, 2))) {
            throw new AssertionError("Remove first matching value");
        }
        LinkedList<String> jobs = new LinkedList<>(Arrays.asList("done:1", "pending:2"));
        Iterator<String> cursor = jobs.iterator();
        while (cursor.hasNext()) {
            if (cursor.next().startsWith("done:")) cursor.remove();
        }
        if (!jobs.equals(Arrays.asList("pending:2"))) {
            throw new AssertionError("Remove completed jobs");
        }
        LinkedList<String> emptyQueue = new LinkedList<>();
        if (emptyQueue.pollFirst() != null) throw new AssertionError("Empty queue");
        System.out.println("3 checks passed");
    }
}

The checks throw directly, so they run without an assertions flag. Value removal and filtering each require a traversal in the worst case. Polling the empty queue is O(1). This is a local verification program, not a server-side code judge.

Connected lessons

Continue with Java LinkedList: operations, internals and failure cases, Java LinkedList quiz.

Common Mistakes

Calling remove(2) removes at index two. A second Iterator.remove without another next is invalid. Test duplicates and an empty list before using the same code for application data.

Add boundary cases that distinguish the overloads

Repeat value removal with a target that is absent and require false without changing membership. Test equal duplicates so the answer proves that only the first matching value is removed. For position removal, test zero, the last valid index and an index equal to size; these cases use a different contract.

For iterator cleanup, put completed jobs at the first and last positions as well as next to each other. A loop that advances twice after removal can skip adjacent matches. Keep the removal on the same iterator that supplied the current element.

A null member can make a polling result ambiguous with an empty queue. Use a non-null element policy for a task queue, and test the policy before insertion. These checks run as a local Java program; they do not describe an online judge or synchronized queue.

java
linkedlist-exercises
Storage details