2 Immutable stacks and queues
This chapter covers
- The compelling benefits and small costs of immutable data structures
- Implementing stacks and queues
- Exploring ways to build an undo-redo stack
- Analyzing time and space complexity
- Implementing the Hughes list
We’ll expand upon the immutable linked list in Chapter 1 to build lists that illustrate diverse concepts. These ideas might already be familiar if you have a background in functional languages; I’ve found they’re less familiar to OO programmers, but they’re powerful tools to add to your problem-solving toolbox.
We’ll start with building an immutable stack by making marginal improvements to our linked list. Once we have immutable stacks we can build an immutable queue, which will show how worst-case performance and average performance amortized over time can be very different. We’ll explore how immutable data structures enable undo-redo logic, and how you can build a mutable interface on top of an immutable data structure. Finally, we’ll look at the Hughes list, a bizarre stack implementation which at first glance appears to contain no actual data and has very different performance characteristics than our run-of-the-mill stack.
In each section we’ll first define the problem we’re attempting to solve with the data structure, create an interface, make some attempts at implementation, and finish up with an informal performance analysis.