Lists Without Arrays
This chapter builds a linked list out of ListItem objects connected by next references and compares it with the array-backed list from earlier chapters. We write each operation as a function over a head reference, first the operations that read the list, then the ones that change its shape. Along the way we keep running into the same problem: the head is stored in the caller’s code, so an operation that changes it cannot update it. Separately, we look at adding a backward link to each item, which gives us a doubly linked list. The chapter ends by comparing the singly linked and doubly linked designs.
After reading this chapter, you should be able to:
- Explain how a linked list stores a sequence as
ListItemobjects connected bynextreferences - Contrast a linked list with an array-backed list in how each stores and connects its items
- Implement the reading operations over a bare chain (traversal,
size,get,set, andcontains), each as a function over a head reference - Change the shape of a list with
addFirst,addLast,insertAfter,insertBefore, andremove, rewiringnextreferences - Return the new head from any operation that changes it
- Explain why the caller must store the returned head back, since a Java method can only hand back one value
- Reason about the cost of each operation, distinguishing an head re-point from an traversal to a position
- Insert beside or remove a
ListItempassed to you directly, rather than reaching it by index - Add a
prevlink to form a doubly linked list, weighing the benefit the extra link gives in operations against the extra bookkeeping it costs
You can download the accompanying code for this chapter: starter and solution.
Sections
- A Different Kind of List
- The ListItem Class
- A Linked List
- Two Kinds of Lists
- Following the Chain
- Traversing a List
- The Size of a List
- Getting an Item by Index
- Setting an Item by Index
- Searching for an Item
- Prepend Operation
- Append Operation
- A Tail Pointer
- Inserting After an Item
- Inserting Before an Item
- Removing an Item
- Getting the Item Itself
- A Backward Link
- Removing a Given Item
- Singly and Doubly Linked Lists