Course contentsShow
← Java
Lesson 1026 of 2,87024. List ImplementationsFree lesson

Removing the Last Element

How unlinkLast() updates tail, nulls out references, and adjusts the new last node's next pointer.

Removing the Last Element

You'll learn how unlinkLast() updates the tail pointer, clears references, and adjusts the new last node's next pointer when removing the final element from a LinkedList.

How Removing the Last Element Works

When you remove the last element from a LinkedList, the unlinkLast() method performs three critical steps to maintain the doubly-linked structure:

Step 1: Update the Tail Reference
The tail pointer currently references the last node. Before removing it, unlinkLast() moves tail backward to point to the second-to-last node. You access this node via tail.prev.

Step 2: Null Out the Old Last Node
To prevent memory leaks, the method nulls out the data and link references in the node being removed. This allows Java's garbage collector to reclaim that memory. Both the item field and the prev pointer are set to null.

Step 3: Adjust the New Last Node's Next Pointer
The node that's now last (the former second-to-last) still has its next pointer referencing the removed node. The method sets this next pointer to null, properly terminating the list.

Visualizing the Process

Imagine a train with three cars: A ↔ B ↔ C. To remove car C:

  1. The "tail" sign moves from C to B
  2. Car C's connections are severed (data cleared, link to B cut)
  3. Car B's forward coupling is locked in the "end of train" position (next = null)

This is an O(1) operation because you have direct access to tail—no traversal needed.

Key Takeaway:
unlinkLast() efficiently removes the last element in constant time by updating tail to the previous node, nulling the removed node's references, and setting the new last node's next pointer to null.