Linked List in Java: Singly, Doubly, Reverse, Cycle Detection and Interview Problems
A beginner-first guide to linked lists in Java: singly and doubly lists, reversing, finding the middle, Floyd cycle detection, merging sorted lists and more interview problems, every solution compiled, run and cross-checked on JDK 25.
An interviewer says “reverse a linked list”. Your lab examiner says “write a menu-driven program for a singly linked list”. A third question asks whether a list has a cycle, and you are not sure what a cycle even means for a list. They sound like three topics, but they all grow from one small idea: a list does not have to live in one block of memory, as long as every item knows where the next one is.
This post builds that idea from nothing, then solves the classic problems in order of difficulty: inserting and deleting, reversing, finding the middle, detecting a cycle, merging two sorted lists, four more interview favourites, and finally the doubly linked list. It replaces two 2015 posts (the singly and the doubly linked list programs) with one article. Every solution was compiled and run on JDK 25, checked against a deliberately slow brute-force version on thousands of random inputs, and every number and console line below is quoted from a file in the companion module; each code block and output block links to the file it came from.
You do not need to know anything about linked lists yet — only what a class and an object reference are. Read straight through the first time. The collapsible “going deeper” panels hold the intermediate and reference-level material, so open them on a second pass.
Versions this was built and run against. JDK 25.0.5.1+2 (Temurin, LTS), JUnit 6.1.3 (the latest GA on the junit-framework releases page; Maven resolved it from Central during the build) and Maven 3.9.11. No other dependencies: the lists are plain Java. Maven Central’s metadata endpoint answered HTTP 429 (rate limited) from the build machine while this was written, which is why the JUnit version was checked against the project’s own release page instead. The module is linked-list in the asmhatre/java-interview-lab repository, and there is no docs/ folder in it: the explanations are in this article.
A linked list is a chain of nodes, and each node knows only what comes next
Picture a treasure hunt. Each clue is a slip of paper that holds a prize and tells you where the next slip is hidden. You cannot jump to clue number five; you start at clue one and follow the trail. A linked list is exactly that: a chain of small objects called nodes, where each node holds a value and a link (an object reference) to the next node. The list itself is only a variable, the head, that points at the first node. The last node’s link is null, meaning “nothing more”, and a head that is null is the empty list.
The picture contrasts the two ways of storing the same four values. An array keeps them side by side, so index 3 is one jump away. The list scatters them and ties them together with links, so reaching the fourth value means following three links from head. Remember that cost; it explains almost everything that follows.
The whole data structure in Java is a class with a value and a link. This is ListNode.java, which every example in this post uses:
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
a.val = 10 a.next.val = 20 a.next.next.val = 30 a.next.next.next = null
whole list from a: 10 -> 20 -> 30 -> null
length: 3
new node 15 points at 20: 15 -> 20 -> 30 -> null
a still reaches the old chain: 10 -> 20 -> 30 -> null
then a.next = the new node: 10 -> 15 -> 20 -> 30 -> null
one new object and one changed link; nothing else moved.
the empty list is null: ListNode.of() == null -> true
Look at what the insertion did: it created one object and changed one link, and nothing else moved. In an array the same insertion would shift every later element one slot to the right. That trade defines the structure — cheap to rearrange, expensive to reach into — and one more fact will matter again and again: each node knows only the node in front of it, never the one behind.
Going deeper: why a Java list never needs “free”, and what null really does here
In Java the nodes are ordinary objects on the heap and a link is just a reference. When no variable can reach a node any more, the garbage collector reclaims it, so deleting a node means unlinking it; there is no separate freeing step as in C. The empty list being null has a practical consequence: every method must decide what to do when head == null, and forgetting that is the most common source of NullPointerException in list code. It is also why ListNode.of() with no values returns null rather than some special empty object.
The same class also builds a list whose last node links back to an earlier one (withCycle), which section 5 needs. A cyclic list breaks the obvious way of printing a list — “follow links until null” — because null never arrives, so ListNode.show stops after 12 nodes and prints ....
ListNode.java — the node class, of, withCycle, and a show that cannot hang
Adding at the front takes two steps; adding at the back means finding the back
To add at the front you need no walking. Make a new node, point it at the old head, and move head to the new node. Two writes, however long the list is. To add at the back, a list that knows only its head has to start at the head and follow links until it finds the node whose link is null, and only then can it attach the new one. The longer the list, the longer that walk.
The diagram shows the front insertion: the new green node is pointed at the old head first, and only then does head move, so the old chain is never lost. The module counts every link it follows (a “hop”), so you can read the cost off a table instead of taking it on trust. The cure for the slow append is a second variable, tail, that always points at the last node; then adding at the back is two writes as well. The class takes a flag, keepTail, so one implementation can show both versions:
/** O(1): the new node points at the old head, then becomes the head. */
public void addFirst(int value) {
head = new ListNode(value, head);
if (tail == null) {
tail = head;
}
size++;
}
/** O(1) with a tail pointer; O(n) without one, because the last node has to be found by walking. */
public void addLast(int value) {
ListNode node = new ListNode(value);
if (head == null) {
head = node;
} else if (keepTail) {
tail.next = node;
} else {
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
hops++;
}
cur.next = node;
}
tail = node;
size++;
}
Those methods are in SinglyLinkedList.java. Here is every operation once, with the errors it throws, and then the number of links each costs for lists of 10, 100 and 1,000 values (02-singly-operations.txt):
addLast(10) -> [10]
addLast(30) -> [10, 30]
add(1, 20) -> [10, 20, 30]
addFirst(5) -> [5, 10, 20, 30]
remove(2) -> removed 20, list [5, 10, 30]
removeLast() -> removed 30, list [5, 10]
removeFirst() -> removed 5, list [10]
indexOf(10) -> 0 indexOf(99) -> -1
empty.removeFirst() throws NoSuchElementException: list is empty
list.get(5) throws IndexOutOfBoundsException: index 5, size 1
Links followed (hops) per operation, on a list that already holds n values:
n | addFirst | addLast no tail | addLast + tail | get(n/2) | indexOf(last) | removeFirst | removeLast
10 | 0 | 36 | 0 | 5 | 9 | 0 | 8
100 | 0 | 4851 | 0 | 50 | 99 | 0 | 98
1000 | 0 | 498501 | 0 | 500 | 999 | 0 | 998
("addLast no tail" and "addLast + tail" are the total hops to build the whole list of n by repeated addLast.)
Read the addLast columns first: building a 1,000-value list by repeated addLast follows 498,501 links without a tail pointer and none with one. Then read get(n/2) and indexOf(last): both follow a number of links proportional to the length, because a linked list has no index arithmetic — get(i) is a walk. And look at the last column: removeLast follows 998 links on a 1,000-value list even though this list has a tail pointer. Section 3 explains why.
Going deeper: where (n−1)(n−2)/2 comes from, and the mistake the test caught
Appending to a list that holds s values follows s−1 links to reach the last node. Building a list of n values one append at a time therefore costs 0 + 1 + 2 + … + (n−2) = (n−1)(n−2)/2 links, which is 36, 4,851 and 498,501 for the three sizes in the table. That is quadratic: ten times the data, a hundred times the walking. With a tail pointer the same build follows no links at all.
I first wrote the assertion as n(n−1)/2 and the build failed with “expected 45 but was 36” for n = 10. The list was right and my arithmetic was off by one append; that is the argument for asserting measured numbers rather than reciting them, and it is why every figure in this post comes from a test that checks it.
add(index, value) follows index−1 links to reach the node before the insertion point; index 0 and index size are delegated to addFirst and addLast so the two special cases are handled in one place.
Deleting changes one link, and the head is the one node with nothing in front of it
To delete a node you never touch the node itself. You go to the node before it and change that node’s link to skip over the doomed one: before.next = doomed.next. After that nothing refers to the deleted node, so the garbage collector can have it. The catch is that you need the node before the one you want, and nodes only point forward, so finding it costs a walk.
In the picture only node 20 changes. The method below is the general case; the transcript from NodesAndOperationsTest.java shows each step on 10, 20, 30, 40 (03-delete-dry-run.txt):
public int remove(int index) {
checkElementIndex(index);
if (index == 0) {
return removeFirst();
}
ListNode before = nodeAt(index - 1);
int value = before.next.val;
before.next = before.next.next;
if (before.next == null) {
tail = before;
}
size--;
return value;
}
remove the node at index 2 from 10 -> 20 -> 30 -> 40:
before: 10 -> 20 -> 30 -> 40 -> null
walk: before = node 20
found: before = 20, doomed = 30, doomed.next = 40
relink: 20.next = 40
after: 10 -> 20 -> 40 -> null
Two positions are special. The head has nothing in front of it, so removing it changes the head variable itself rather than a node’s link; and the last node needs the walk described above, after which tail must be moved back one node:
removing the head has no node before it, so the head variable itself changes:
before: head -> 10 -> 20 -> 30 -> null
head = head.next
after: head -> 20 -> 30 -> null
removing the tail needs the node before it, so it must be found by walking (and then tail moves back):
list 10, 20, 30, 40, 50: removeLast() returned 50 after following 3 links; list is now [10, 20, 30, 40]
The head is a special case, and getting it wrong fails silently. A common first attempt for “remove every node holding this value” looks one node ahead (cur.next.val == value), so it never examines the head itself. Asked to remove 1 from 1 → 2 → 3 it returns the list unchanged: no exception, no warning. The fix is a dummy node placed in front of the head, so that the head has a node before it like every other node. You will meet the dummy node again in section 6. Both versions are in Pitfalls.java; the transcript is 12-pitfalls.txt.
2. Remove the value 1 from 1 -> 2 -> 3, looking only one node ahead:
wrong: 1 -> 2 -> 3 -> null (nothing was removed, and no error)
with a dummy node in front: 2 -> 3 -> null
/** The fix: a dummy node in front of the head makes "remove the head" the same as "remove any other node". */
public static ListNode removeValue(ListNode head, int value) {
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == value) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummy.next;
}
Going deeper: why removeLast is slow even with a tail pointer, and the 2015 removeFirst that returned 0 for “nothing”
The tail pointer tells you where the last node is, but removing it means setting the previous node’s link to null and moving tail back to that previous node, and no node points backwards. So the walk is unavoidable: on a list of 5 values it follows 3 links (03-delete-dry-run.txt):
list 10, 20, 30, 40, 50: removeLast() returned 50 after following 3 links; list is now [10, 20, 30, 40]
A singly linked list can make the front cheap in both directions (add and remove) and the back cheap in one (add). Making the back cheap in both is exactly what the second link in section 8 is for.
The 2015 program had a quieter flaw in the same area. When asked to remove from an empty list it printed a message and returned 0 — but 0 is also a perfectly good value to have stored. A caller that looks only at the return value cannot tell “removed a zero” from “there was nothing to remove”. The version in this module throws NoSuchElementException instead, like java.util does:
2015 list holding the value 0: removeFirst() returned 0
2015 list that is empty: removeFirst() returned 0 (and printed: List is empty - nothing to remove)
A caller that only looks at the return value cannot tell these two cases apart.
this module, list holding 0: removeFirst() returned 0
this module, now empty: removeFirst() throws NoSuchElementException: list is empty
Reversing a list means turning every link around — after saving the next node
Reversal is the most-asked linked-list question, and it is one idea: walk the list once, and at each node make its link point at the node you just left instead of the node ahead. The danger is in the order of the writes. The moment you overwrite a node’s link you lose the way forward, so the loop’s first act is to write down the next node. Three variables do the job: prev (the part already reversed), cur (the node being turned) and next (saved so the walk is not lost).
The figure freezes the loop after two passes. The finished green half already points backwards; the blue half has not been touched; and the only thing joining the two halves is the pair of variables prev and cur. That is why the order matters: nothing in the list itself remembers where 3 is once node 2’s link has been turned.
The method (LinkedListProblems.java):
/** Reverse in place with three pointers. O(n) time, O(1) space. */
public static ListNode reverseIterative(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next; // remember the rest before we cut the link
cur.next = prev; // turn this node around
prev = cur;
cur = next;
}
return prev;
}
And the same loop with every pass printed, on 1 → 2 → 3 → 4 (04-reverse-dry-run.txt). Watch reversed grow from the left while still to do shrinks from the right:
start prev=null cur=1 reversed: null still to do: 1 -> 2 -> 3 -> 4 -> null
pass 1 prev=1 cur=2 reversed: 1 -> null still to do: 2 -> 3 -> 4 -> null
pass 2 prev=2 cur=3 reversed: 2 -> 1 -> null still to do: 3 -> 4 -> null
pass 3 prev=3 cur=4 reversed: 3 -> 2 -> 1 -> null still to do: 4 -> null
pass 4 prev=4 cur=null reversed: 4 -> 3 -> 2 -> 1 -> null still to do: null
The classic slip: reading cur.next after you have overwritten it. Writing cur.next = prev; prev = cur; cur = cur.next; looks harmless, but by the last line cur.next is the node you just came from, so the loop ends after one pass and the rest of the list is gone (the wrong version is in Pitfalls.java; the run is 12-pitfalls.txt):
1. Reverse that reads cur.next after overwriting it, on 1 -> 2 -> 3 -> 4:
wrong: 1 -> null
correct: 4 -> 3 -> 2 -> 1 -> null
Going deeper: the recursive version, and the stack limit it runs into
The recursive version asks the question differently: reverse everything after the head, then hang the head on the end of that reversed chain. This is also in LinkedListProblems.java:
/** Reverse by trusting the recursion to reverse the tail. O(n) time, but O(n) stack depth. */
public static ListNode reverseRecursive(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseRecursive(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
It is shorter and gives the same answers, but it uses one stack frame per node. The iterative version has no such limit, which the module demonstrates on a thread with a 1 MB stack:
iterative, 1,000,000 nodes: first value after reversing = 999999 (no problem)
recursive, 1,000 nodes on a 1 MB thread stack: ok
recursive, 1,000,000 nodes on a 1 MB thread stack: StackOverflowError
Neither time nor space matters for a ten-node lab exercise, but for an interview the follow-up is always “what happens on a million nodes?” — and now you have the transcript that answers it. The iterative form is O(n) time and O(1) extra space; the recursive form is O(n) time and O(n) stack.
DryRuns.java — the instrumented copy that prints each pass
A slow pointer and a fast pointer find the middle — and catch cycles too
How do you find the middle of a list whose length you do not know, without walking it twice? Send two pointers from the head: slow moves one link per step and fast moves two. When fast reaches the end, slow has covered half the distance, so it stands at the middle.
/** The middle node; for an even length, the second of the two middles. O(n) time, O(1) space. */
public static ListNode middle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
For an even length the loop stops with slow on the second of the two middle nodes, which the transcript makes explicit (05-middle-and-cycle.txt):
Middle node of 1 -> 2 -> ... -> n (for even n, the second of the two middles):
n = 1 -> middle value 1 (index 0)
n = 2 -> middle value 2 (index 1)
n = 3 -> middle value 2 (index 1)
n = 4 -> middle value 3 (index 2)
n = 5 -> middle value 3 (index 2)
n = 6 -> middle value 4 (index 3)
n = 7 -> middle value 4 (index 3)
n = 8 -> middle value 5 (index 4)
The same two pointers also answer a stranger question: does this list contain a cycle, a node whose link points back at an earlier node so that the list never ends? Following links until null would loop forever, but two pointers at different speeds cannot avoid each other inside a ring. Fast gains one node on slow every step, so it cannot jump over it — sooner or later they land on the same node. This is Floyd’s tortoise-and-hare algorithm.
In the diagram the last node, −4, links back to 2, so nodes 2, 0 and −4 form a ring with node 3 as a lead-in. If there is no ring, fast reaches null first and the answer is “no cycle”. The code is the middle-node loop plus one comparison:
/** Floyd's tortoise and hare. O(n) time, O(1) space. */
public static boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
And the trace the module prints for exactly that ring, one line per step (MiddleAndCycleTest.java):
Floyd's algorithm on 3 -> 2 -> 0 -> -4 whose last node links back to index 1:
list: 3 -> 2 -> 0 -> -4 -> ... (last node links back to index 1)
step 0 slow at index 0 fast at index 0
step 1 slow at index 1 fast at index 2
step 2 slow at index 2 fast at index 1
step 3 slow at index 3 fast at index 3
they meet at index 3 after 3 steps: there is a cycle
phase 2: probe at index 0, slow at index 3
phase 2: probe at index 1, slow at index 1
they meet again at index 1 after 1 steps: that is where the cycle starts
The loop condition has two parts for a reason. Writing while (fast != null) and then reading fast.next.next works on even-length lists and throws NullPointerException on odd-length ones, because fast.next can be null when fast is not. Both checks — fast != null && fast.next != null — are needed (the wrong version is in Pitfalls.java; the run is 12-pitfalls.txt):
3. Cycle check that tests fast but not fast.next, on the plain list 1 -> 2 -> 3:
wrong: throws NullPointerException
correct: hasCycle = false
Going deeper: finding where the cycle starts, and why that works
Knowing that a cycle exists is half the interview question; the other half is “which node does it start at?” After the pointers meet, leave slow where it is, put a second pointer back at the head, and move both one link at a time. They meet again exactly at the first node of the cycle. In LinkedListProblems.java:
/** The node where the cycle begins, or null when there is no cycle. */
public static ListNode cycleStart(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode probe = head;
while (probe != slow) {
probe = probe.next;
slow = slow.next;
}
return probe;
}
}
return null;
}
/** Number of nodes in the cycle, or 0 when there is none. */
public static int cycleLength(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
int length = 1;
for (ListNode cur = slow.next; cur != slow; cur = cur.next) {
length++;
}
return length;
}
}
return 0;
}
Why it works: call the number of nodes before the cycle μ and the cycle’s length λ. When the pointers first meet, slow has taken t steps and fast has taken 2t, and they are at the same place in the ring, so t must be a multiple of λ (and at least μ, because slow cannot be in the ring before it has walked μ steps). Slow then stands (t−μ) mod λ nodes into the ring, which, since t is a multiple of λ, is the same as −μ mod λ. Walking μ more steps from there lands on offset 0: the start of the cycle. The head pointer needs exactly μ steps to reach the same node. Rather than ask you to trust the algebra, the test runs the real algorithm on every shape with μ from 0 to 30 and λ from 1 to 30 and checks the meeting step, the second-phase length and the landing node each time (05-middle-and-cycle.txt):
Why the second phase works. Tail length mu (nodes before the cycle) and cycle length lambda:
mu lambda | steps until they meet | meet at index | phase-2 steps | cycle starts at index
0 4 | 4 | 0 | 0 | 0
1 10 | 10 | 10 | 1 | 1
3 4 | 4 | 4 | 3 | 3
4 4 | 4 | 4 | 4 | 4
5 4 | 8 | 8 | 5 | 5
7 3 | 9 | 9 | 7 | 7
30 30 | 30 | 30 | 30 | 30
checked all 930 combinations of mu = 0..30 and lambda = 1..30: the formulas held every time.
The obvious alternative is to remember every node you have seen in a set and stop at the first repeat. It works, but it stores every node, while Floyd holds two references:
Memory: on a 100000-node ring, a set of seen nodes holds 100000 entries before it finds the repeat;
Floyd holds exactly two references (slow and fast) and reaches the same answer: hasCycle = true
Cycle detection on Wikipedia, for the history and the alternative (Brent’s) algorithm
Merging two sorted lists is easy once a dummy node removes the special case
Given two lists that are each already sorted, build one sorted list: compare the front node of each, take the smaller, and repeat. Two details make it clean. First, the result needs a starting point, and the very first node you take has no previous node to hang from — the same head problem as in section 3, solved the same way, with a dummy node whose next is the answer. Second, no new nodes are created: merging only relinks the ones that already exist.
The figure merges 1, 3, 5 with 2, 4, 6, 8, 9. Blue nodes came from the first list and amber from the second. When the first list runs out, what is left of the second (6, 8, 9) is already sorted and already linked, so it is attached whole with a single write rather than copied node by node.
/** Merge two sorted lists by relinking their nodes; no new nodes. O(n + m) time, O(1) space. */
public static ListNode mergeSorted(ListNode a, ListNode b) {
ListNode dummy = new ListNode(0); // a fake head so the first node is not a special case
ListNode tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = (a != null) ? a : b; // one list is used up; the other is already sorted, so attach it whole
return dummy.next;
}
Merge 1 -> 3 -> 5 and 2 -> 4 -> 6 -> 8 -> 9:
a: 1 -> 3 -> 5 -> null b: 2 -> 4 -> 6 -> 8 -> 9 -> null
compare 1 with 2 -> take 1 from a
merged so far: [1]
compare 3 with 2 -> take 2 from b
merged so far: [1, 2]
compare 3 with 4 -> take 3 from a
merged so far: [1, 2, 3]
compare 5 with 4 -> take 4 from b
merged so far: [1, 2, 3, 4]
compare 5 with 6 -> take 5 from a
merged so far: [1, 2, 3, 4, 5]
one list is empty; attach the rest of the other whole: 6 -> 8 -> 9 -> null
result: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 8 -> 9 -> null
Forgetting the leftover. A loop that runs while (a != null && b != null) stops as soon as one list is used up, and if the last line that attaches the rest of the other list is missing, the leftover nodes are silently dropped. The result still looks like a sorted list, which is what makes the bug easy to miss (the wrong version is in Pitfalls.java; the run is 12-pitfalls.txt):
Going deeper: cost, and how this becomes merge sort
Each comparison moves one node into the result, so merging lists of lengths n and m is O(n + m) time and O(1) extra space — no array, no copies. Sorting a whole linked list with merge sort is built from two pieces you now have: find the middle with the slow and fast pointers (section 5) to split the list in two, sort each half the same way, and merge the results with this method. This module does not implement the full sort; the point is that the pieces you have already seen are the ones it needs.
Four more problems you will be asked, each a small variation on what you have seen
Each of these reuses a trick from an earlier section: two pointers kept a fixed distance apart, reversing half the list, a dummy node, and walking two lists at once. They are collapsed so the page stays readable; open the ones you want. All four are in LinkedListProblems.java, and the transcript for every one is 06-more-problems.txt.
Problem: remove the n-th node from the end, in one pass
The obvious way is two passes: count the nodes, then walk to the right place. The one-pass way keeps two pointers exactly n nodes apart. Send the lead pointer n steps ahead, then move both until lead is on the last node; lag is then standing just before the node to delete. The dummy node makes removing the head (n equal to the length) the same as every other case. The method (LinkedListProblems.java) and its output (06-more-problems.txt) are:
/** Remove the n-th node from the end (n = 1 is the last node) in one pass with two pointers n apart. */
public static ListNode removeNthFromEnd(ListNode head, int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be at least 1");
}
ListNode dummy = new ListNode(0, head);
ListNode lead = dummy;
ListNode lag = dummy;
for (int i = 0; i < n; i++) {
lead = lead.next;
if (lead == null) {
throw new IllegalArgumentException("n = " + n + " is longer than the list");
}
}
while (lead.next != null) {
lead = lead.next;
lag = lag.next;
}
lag.next = lag.next.next;
return dummy.next;
}
Remove the n-th node from the end of 1 -> 2 -> 3 -> 4 -> 5:
n = 1 -> 1 -> 2 -> 3 -> 4 -> null
n = 2 -> 1 -> 2 -> 3 -> 5 -> null
n = 3 -> 1 -> 2 -> 4 -> 5 -> null
n = 4 -> 1 -> 3 -> 4 -> 5 -> null
n = 5 -> 2 -> 3 -> 4 -> 5 -> null
n = 4 on a 3-node list throws IllegalArgumentException: n = 4 is longer than the list
Problem: is the list a palindrome?
A palindrome reads the same in both directions, but a singly linked list can only be read in one. The O(1)-space answer combines two earlier sections: find the middle (section 5), reverse the second half in place (section 4), compare the two halves, and then reverse the second half again so the caller’s list is left exactly as it was. The method (LinkedListProblems.java) and its output (06-more-problems.txt) are:
/** Palindrome check in O(1) extra space: reverse the second half, compare, then put it back. */
public static boolean isPalindrome(ListNode head) {
ListNode mid = middle(head);
ListNode right = reverseIterative(mid);
ListNode left = head;
boolean same = true;
for (ListNode r = right; r != null; r = r.next, left = left.next) {
if (r.val != left.val) {
same = false;
break;
}
}
reverseIterative(right); // restore the list for the caller
return same;
}
Palindrome check (the list is put back the way it was):
1 -> 2 -> 3 -> 2 -> 1 -> null -> true list afterwards: 1 -> 2 -> 3 -> 2 -> 1 -> null
1 -> 2 -> 2 -> 1 -> null -> true list afterwards: 1 -> 2 -> 2 -> 1 -> null
1 -> 2 -> 3 -> 4 -> null -> false list afterwards: 1 -> 2 -> 3 -> 4 -> null
7 -> null -> true list afterwards: 7 -> null
null -> true list afterwards: null
The last two lines of the output are the edge cases worth testing: a single node and the empty list are both palindromes, and an empty list must not crash.
Problem: remove duplicates from a sorted list
Because the list is sorted, equal values sit next to each other, so a single walk suffices: if the next node has the same value, skip it by relinking; otherwise move forward. Note the else: after skipping, the loop must not advance, because the node after the skipped one might be a duplicate too. The method (LinkedListProblems.java) and its output (06-more-problems.txt) are:
/** Drop repeated values from a sorted list, keeping one of each. */
public static ListNode removeDuplicatesSorted(ListNode head) {
ListNode cur = head;
while (cur != null) {
if (cur.next != null && cur.next.val == cur.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
Problem: where do two lists join?
Two lists can share a tail: different heads, then the very same nodes from some point on. Walk a pointer along each list, and when one reaches the end, send it to the head of the other list. Both pointers then travel the same total distance (the lengths added together), so if the lists join they arrive at the joining node at the same moment, and if they do not they both arrive at null together. The method is in LinkedListProblems.java:
/** The node where two acyclic lists join (same node object, not just equal values), or null. */
public static ListNode intersection(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = (a == null) ? headB : a.next; // after finishing one list, continue along the other
b = (b == null) ? headA : b.next;
}
return a;
}
The comparison must be by identity (a != b on references), not by value. Two separate lists that merely contain the same numbers are not joined, and comparing values would say they are (outputs: 06-more-problems.txt and 12-pitfalls.txt):
Intersection: a = 4 -> 1 -> 8 -> 4 -> 5 -> null b = 5 -> 6 -> 1 -> 8 -> 4 -> 5 -> null (the 8 -> 4 -> 5 tail is one shared chain)
the lists join at the node holding 8; both 1s before it are different nodes with the same value
a list that merely has the same values 8 -> 4 -> 5 but its own nodes: intersection = null
5. Comparing nodes by value when the question is about identity (the intersection problem):
two separate lists 8 -> 4 -> 5: same value at the head? true same node? false
A second link, pointing backwards, makes unlinking a known node instant
Several of the costs above trace to one fact: a node knows only what is in front of it. Give each node a second link, prev, pointing at the node behind it, and you have a doubly linked list. The price is one extra reference per node and twice as many links to keep correct on every change. The reward is that a node you are already holding can be unlinked without walking anywhere.
The picture unlinks B. Because B knows both neighbours, the two writes A.next = C and C.prev = A are all it takes; in a singly linked list the first of those needs the node before B, and finding it means walking from the head. The list also keeps both a head and a tail, so adding or removing at either end is O(1). Here are the two methods that carry the idea, both from DoublyLinkedList.java:
/** Four pointer writes. The else branch is the one the 2015 insertAfter forgot. */
public Node addAfter(Node node, int value) {
Node added = new Node(value);
added.prev = node;
added.next = node.next;
if (node.next != null) {
node.next.prev = added;
} else {
tail = added;
}
node.next = added;
size++;
return added;
}
/** Unlinks a node in O(1) because it already knows both neighbours. */
public int remove(Node node) {
if (node.prev != null) {
node.prev.next = node.next;
} else {
head = node.next;
}
if (node.next != null) {
node.next.prev = node.prev;
} else {
tail = node.prev;
}
node.prev = null;
node.next = null;
size--;
return node.val;
}
addAfter(the last node, 99): the tail has to move, and it does
forward: [40, 65, 20, 45, 60, 99]
backward: [99, 60, 45, 20, 65, 40]
last().val = 99, removeLast() returned 99
Links followed to reach one element of a 1000-element list:
index | doubly (nearer end) | singly (from head)
0 | 0 | 0
250 | 250 | 250
499 | 499 | 499
500 | 499 | 500
750 | 249 | 750
999 | 0 | 999
Unlinking the element at index 700 when you already hold the node:
doubly: 0 links followed (the node knows its neighbours)
singly: 699 links followed (it must walk to the node before it)
Two things stand out. Reaching an element starts from whichever end is nearer, so no lookup follows more than half the list. And unlinking a node you already hold follows no links at all, against 699 for the singly linked list, which has to find the node before it. That second fact is why a doubly linked list shows up inside caches, such as the LRU cache linked at the end of this section.
A real bug in the 2015 doubly linked list. Writing addAfter for this module, the branch that moves tail when you insert after the last node was obviously needed — and the 2015 program did not have it. Its insertAfter linked the new node in but never updated last, so the list had one more node than its own tail pointer knew about. The transcript reproduces what that costs (LegacyBugsTest.java). The program is unchanged in LegacyDoublyDemo.java, so you can run the bug yourself.
2015 DoublyLinkedList: insertAtLast(1), insertAtLast(2), insertAtLast(3), then insertAfter(4, position 3)
Forward: 1 2 3 4
Reverse: 3 2 1
last.data = 3 (the new node 4 is the real last node, but 'last' was never moved)
deleteLast() returned 3; forward now: Forward: 1 2
it should have removed only 4 and returned 4; instead both 3 and 4 are gone and the caller saw only the 3.
deleteLast() was supposed to remove 4 and return 4; instead both 3 and 4 vanished and the caller saw only the 3. With the tail update in place, the same operations give (08-legacy-bugs.txt):
the DoublyLinkedList in this module, same operations:
forward: [1, 2, 3, 4]
backward: [4, 3, 2, 1]
removeLast() returned 4
Going deeper: java.util.LinkedList is a doubly linked list, and where the second link earns its keep
The JDK’s own LinkedList is this structure. The module reads it rather than recalling it: reflection shows the private node class has an item and both a next and a prev, and the source of the method that finds the i-th node confirms the nearer-end rule used above:
JDK: 25.0.5.1+2-LTS
fields of java.util.LinkedList$Node (reflection): [Node next, Node prev, Object item]
interfaces of java.util.LinkedList: [List, Deque, Cloneable, Serializable]
java/util/LinkedList.java, node(int index), from line 578:
578 Node<E> node(int index) {
579 // assert isElementIndex(index);
580
581 if (index < (size >> 1)) {
582 Node<E> x = first;
583 for (int i = 0; i < index; i++)
584 x = x.next;
585 return x;
586 } else {
587 Node<E> x = last;
588 for (int i = size - 1; i > index; i--)
589 x = x.prev;
590 return x;
591 }
592 }
Doubly linked lists matter most where you keep hold of nodes and rearrange them often. An LRU cache is the standard example: a hash map finds the node for a key in O(1), and the doubly linked list lets that node be unlinked and moved to the front in O(1) because it knows both its neighbours — the full build is in LRU Cache in Java: LinkedHashMap, HashMap + Doubly Linked List and a Thread-Safe Version.
A solution that passes the three examples in a blog post can still be wrong, so every list class and every problem here was checked against something obviously correct on random input. Both list classes were run through 2,000 random sequences of 100 operations each and compared with java.util.ArrayList after every single step (RandomAgreementTest.java). The singly list was run both with and without its tail pointer; the doubly list was also checked backwards through its prev links after every step:
seed 2026, 2,000 sequences of 100 operations per class, each step compared with the reference
SinglyLinkedList 200,000 steps compared, 0 disagreements
DoublyLinkedList 200,000 steps compared (forward and backward), 0 disagreements
Every interview problem was compared against a brute-force twin in BruteForce.java that shares no code with it — arrays, sorting and sets of already-seen nodes instead of pointer tricks — on 5,000 seeded random lists each:
seed 2026, 5,000 random cases per problem
problem cases disagreements
reverse (iterative, recursive) 5,000 0
middle 5,000 0
mergeSorted 5,000 0
removeNthFromEnd 5,000 0
isPalindrome 5,000 0
removeDuplicatesSorted 5,000 0
hasCycle / cycleStart / cycleLength 5,000 0
intersection 5,000 0
The seed is fixed, so a failure would be reproducible rather than flaky, and the assertions would stop the build before any of these numbers could be written to a file.
Going deeper: what the brute-force versions do, and what these checks cannot show
The brute-force twins are deliberately naive: reversing copies the values into an array backwards, “has a cycle” is “does a set of node identities see the same node twice”, merging concatenates and sorts. Their only job is to be too simple to be wrong. A test like this shows that the clever version agrees with the simple one on small random inputs; it does not prove correctness for all inputs, and it says nothing about speed. Where this post makes a performance claim it counts links followed, which is exact for the shape of the algorithm, rather than timing it, which would depend on the machine.
The 2015 menu-driven programs are still here, and still run
The two posts this article replaces each ended with a console program: a menu that lets you insert, remove, search and display on a linked list, with a sample session. Both are kept in the module as LegacySinglyDemo.java and LegacyDoublyDemo.java. The list logic is unchanged; only two things moved so a test could drive them — the classes became inner classes, and output goes through a PrintStream instead of System.out. The test feeds each one the original keystrokes and checks the result against the 2015 sample output character for character.
The original singly linked list menu program and its sample session
Insert at the first position, the last position or a given 1-based position; remove first, last or at a position; search; display. The first lines of the session, which is identical to the 2015 sample (the whole run is 13-singly-session.txt):
keystrokes: 1 2 10 1 3 50 1 1 20 2 1 3 90 4 3 50 3 1 2 1 2 2 4 1 3 80 4 2 3 2 4 5
output identical to the 2015 article's sample output: true
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 2
Enter element: 10
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 3
Enter element: 50
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 1
Enter element: 20
Enter position: 2
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 1
1. Insert at position
2. Insert at first
3. Insert at last
Enter choice: 3
Enter element: 90
--- Singly Linked List Menu ---
1. Insert
2. Remove
3. Search
4. Display
5. Exit
Enter choice: 4
List: 10 20 50 90
Two things to know about it: its removeFirst returns 0 for an empty list (see the sentinel-value discussion in section 3), and it walks from the head on every insertLast because it keeps no tail pointer, which the table in section 2 puts a number on.
LegacySinglyDemo.java — the 2015 program (java LegacySinglyDemo.java runs it interactively)
The original doubly linked list menu program and its sample session
The same menu plus insert-after and insert-before a position, and forward or reverse display. The first lines of the session, identical to the 2015 sample (the whole run is 14-doubly-session.txt):
keystrokes: 1 1 20 1 1 40 1 2 60 1 3 45 2 1 4 65 2 3 1 3 2 2 1 2 2 3 1 4 20 2 3 2 3 1 5
output identical to the 2015 article's sample output: true
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 1
1. Insert at first
2. Insert at last
3. Insert after position
4. Insert before position
Select: 1
Enter element: 20
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 1
1. Insert at first
2. Insert at last
3. Insert after position
4. Insert before position
Select: 1
Enter element: 40
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 1
1. Insert at first
2. Insert at last
3. Insert after position
4. Insert before position
Select: 2
Enter element: 60
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 1
1. Insert at first
2. Insert at last
3. Insert after position
4. Insert before position
Select: 3
Enter element: 45
Enter position: 2
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 1
1. Insert at first
2. Insert at last
3. Insert after position
4. Insert before position
Select: 4
Enter element: 65
Enter position: 2
--- Doubly Linked List Menu ---
1. Insert
2. Remove
3. Display list
4. Search
5. Exit
Select option: 3
1. Forward display
2. Reverse display
Select: 1
Forward: 40 65 20 45 60
Notice that this sample never exercises the one case that is broken: it never inserts after the last node, which is why the bug in section 8 survived. A sample session shows that something works; only a test that tries the edges shows that it works everywhere.
For exams and interviews, yes; for production code, almost never. Linked-list questions test whether you can manipulate references without losing the rest of the chain, and that is worth practising. In real programs java.util.LinkedList already exists, and as section 8 showed, it is the same structure you have just built. Its O(1) insertion and removal only pay off when you already hold the position (an iterator, or a node of your own, as in an LRU cache); looking an element up by index is still a walk. This module counts links followed, not nanoseconds, so it cannot tell you whether a linked list beats an array-backed list on your hardware for your data. If that decision matters, measure it with a proper benchmark harness such as JMH rather than reasoning from the textbook costs.
No Comments yet!