Skip to content
Preview · sample content · Explore all pages

Java LinkedList exercises with checked solutions

Last updated: 28 Sept 20263 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.

java
linkedlist-exercises
Storage details