Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

3.4 Edge Cases

How it works

The empty list, the single-element list, and operations at the head or tail are where implementations break, because those are the cases where a reference is null.

Handle head and tail explicitly before writing the general middle case.

Common error

Writing the general case first and patching the ends afterwards, which usually leaves one broken.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

LinkedList<Integer> values = new LinkedList<Integer>();
values.addFirst(8);
System.out.println(values.removeFirst());
System.out.println(values.isEmpty());

Output

8
true

An empty list and a one-node list need explicit consideration. Removing the sole element must restore a consistent empty state, including any stored head, tail, and size information.

Exercises

3.4.1 · Explain

Why can removing the sole node leave a bug when tail is not reset?

Show solution

The structure may claim to be empty through head while tail still refers to an old node, breaking later insertions or consistency checks.

3.4.2 · Write code

Use LinkedList to add and remove one value, then safely inspect the empty front with peekFirst.

Show solution

The non-throwing peek reports null when no element exists.

One valid solution

LinkedList<String> q = new LinkedList<String>();
q.add("A"); q.removeFirst();
System.out.println(q.peekFirst());

Expected output

null
Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic