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 started with a gentle introduction to review the basics; we’ll expand upon the immutable list in Chapter 1 to build some different kinds of lists to illustrate a few diverse concepts. We’ll build 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 amortized-case performance 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.
Before we get into any of that though, I should say what compelling benefits changed how I approached programming; I strongly prefer immutable data structures over their mutable counterparts.