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

Adding Elements to the End

Step-by-step: linkLast() method updates tail reference and adjusts next pointer of old last node.

Adding Elements to the End

You'll learn how LinkedList efficiently appends elements by updating its tail reference and connecting the old last node to the new one.

The linkLast() Method Step-by-Step

When you add an element to the end of a LinkedList, Java uses the linkLast() method internally. This operation is remarkably efficient because LinkedList maintains a tail reference pointing directly to the last node—no traversal needed.

How It Works

Think of a train where you know exactly where the caboose is. Adding a new car to the end doesn't require walking from the engine; you go straight to the caboose and attach the new car.

Here's what happens inside linkLast():

  1. Create a new node with the element you're adding
  2. Check if the list is empty:
    • If empty, both head and tail point to this new node
    • If not empty, proceed to step 3
  3. Update the old tail node's next pointer to reference the new node
  4. Update the new node's prev pointer to reference the old tail
  5. Move the tail reference to point to the new node
  6. Increment the size counter

Why This Is Fast

Because LinkedList stores a direct reference to the tail, you don't need to traverse from the head through every node. You jump straight to the end, update two pointers, and you're done—constant time O(1).

This contrasts with adding to the beginning (which you learned with linkFirst()), but uses the same principle: direct reference access plus pointer manipulation.

Key Takeaway: Adding to the end of a LinkedList uses linkLast(), which leverages the tail reference to update the old last node's next pointer and move the tail reference forward—all in O(1) time.