Building a LinkedList
Last chapter left head, tail, and size as loose variables the caller had to keep in sync, with the list’s ListItem structure exposed to anyone using it. This chapter wraps that structure in a LinkedList<T> class that owns its own state and hides the internals. It also shows how to use sentinel nodes to remove the boundary-case branches that make the code more complex.
After reading this chapter, you should be able to:
- Motivate a
LinkedListabstraction in terms of encapsulation, information hiding, and the invariants a class can keep that loosehead/tail/sizevariables cannot - Define a
LinkedList<T>that ownshead,tail, andsizebehind a private generic doubly linkedNode<T>, separating the public list operations from the private node details - Implement the access and search operations (a private
node(index)helper,get/set, andindexOf/containswithObjects.equals) and explain why indexed access is - Implement
add,remove(index), andremove(value), keeping thehead,tail, andsizeinvariants correct as nodes are inserted and unlinked - Compare the operation costs of
LinkedListandDynamicArray, and choose the implementation that fits a given access or update pattern - Explain how front and back sentinel nodes remove the list’s boundary-case branches
You can download the accompanying code for this chapter: starter and solution.