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():
- Create a new node with the element you're adding
- Check if the list is empty:
- If empty, both head and tail point to this new node
- If not empty, proceed to step 3
- Update the old tail node's
nextpointer to reference the new node - Update the new node's
prevpointer to reference the old tail - Move the tail reference to point to the new node
- 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.