You are on page 1of 23

Data Abstraction & Problem

Solving with C++


WALLS AND MIRRORS
SIXTH EDITION

Frank M. Carrano
University of Rhode Island

Timothy Henry

University of Rhode Island

2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

the publication of the rst edition, we all have gained experience with teaching data abstraction in an objectoriented way using C++. This edition reects that experience and the many comments and suggestions received
from faculty and students alike.
I am happy to introduce Dr. Timothy Henry, my co-author and colleague at the University of Rhode Island.
Together, we have given this book a much needed revision and a new look. However, our goal remains to give
students a superior foundation in data abstraction, object-oriented programming, and other modern problemsolving techniques. All C++ code has been rewritten with a focus on safe and secure programming practices. It
also adheres to the C++11 standard.
We hope that you enjoy reading this book. Like many others before you, you can learnor teachdata
structures in an effective and sustainable way.

Welcome

Welcome to the sixth edition of Data Abstraction & Problem Solving with C++: Walls and Mirrors. Since

Talk to Us
Walls and Mirrors continues to evolve.Your comments, suggestions, and corrections will be greatly appreciated. Here
are a few ways to reach us:

E-mail: carrano@acm.org
Facebook: www.facebook.com/makingitreal
Twitter: twitter.com/Frank_M_Carrano
Blog: frank-m-carrano.com/makingitreal

iii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

A Note to Students

The topics that we cover in this book deal with the various ways of organizing data so that a given application
can access and manipulate data in an efcient way. These topics are fundamental to your future study of computer science, as they provide you with the foundation of knowledge required to create complex and reliable software. Whether you are interested in designing video games or software for robotic-controlled surgery, the study
of data structures is vital to your success. Even if you do not study all of the topics in this book now, you are
likely to encounter them later. We hope that you will enjoy reading the book, and that it will serve as a useful
reference tool for your future courses.
The walls and mirrors in the title represent two fundamental problem-solving techniques that appear
throughout the presentation. Data abstraction isolates and hides the implementation details of a module from the
rest of the program, much as a wall can isolate and hide you from your neighbor. Recursion is a repetitive technique that solves a problem by solving exactly the same but smaller problems, much as images in facing mirrors
grow smaller with each reection.
Please be sure to browse the rest of this preface to see the features that will help you in your studies. To help
you learn and to review for exams, we have included such learning aids as video tutorials (VideoNotes), checkpoint questions with answers, margin notes, programming tips, chapter summaries, and a glossary. As a help
during programming, you will nd C++ reference material in the appendices and inside the covers. You should
review the list of this books features given later in this preface in the section Features to Enhance Learning.
The presentation makes some basic assumptions about your knowledge of C++. Some of you may need to
review this language or learn it for the rst time by consulting the appendices of this book. This book covers C++
classes and other relevant aspects of the language in new C++ Interludes that occur throughout the book between certain chapters. These interludes do not assume that you already know their topics. We assume no experience with recursive functions, which are included in Chapters 2 and 5.
All of the C++ source code that appears in this book is available for your use. Later in this preface, the description of supplementary materials tells you how to obtain these les, as well as the VideoNotes and other online documents.

iv
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

This books organization, sequencing, and pace of topic coverage make learning and teaching easier by focusing
your attention on one concept at a time, by providing exibility in the order in which you can cover topics, and by
clearly distinguishing between the specication and implementation of abstract data types, or ADTs. To accomplish
these goals, we have organized the material into 21 chapters. Most chapters focus on either the specication and use of
an ADT or its various implementations. You can choose to cover the specication of an ADT followed by its implementations, or you can treat the specication and use of severalADTs before you consider any implementation issues.
The books organization makes it easy for you to choose the topic order that you prefer.

Table of Contents at a Glance


The following list shows the overall composition of the book. A further chapter-by-chapter description appears
later. Note that gray highlighted sections are available online.
Chapter 1
Data Abstraction: The Walls
C++ Interlude 1
C++ Classes
Chapter 2
Recursion: The Mirrors
Chapter 3
Array-Based Implementations
C++ Interlude 2
Pointers, Polymorphism, and Memory Allocation
Chapter 4
Link-Based Implementations
Chapter 5
Recursion as a Problem-Solving Technique
Chapter 6
Stacks
C++ Interlude 3
Exceptions
Chapter 7
Stack Implementations
Chapter 8
Lists
Chapter 9
List Implementations
Chapter 10
Algorithm Efciency
Chapter 11
Sorting Algorithms and Their Efciency
C++ Interlude 4
Class Relationships and Reuse
Chapter 12
Sorted Lists and Their Implementations
Chapter 13
Queues and Priority Queues
Chapter 14
Queue Implementations
C++ Interlude 5
Overloaded Operators and Friend Access
Chapter 15
Trees
Chapter 16
Tree Implementations
C++ Interlude 6
Iterators
Chapter 17
Heaps
Chapter 18
Dictionaries and Their Implementations
Chapter 19
Balanced Search Trees
Chapter 20
Graphs
Chapter 21
Processing Data in External Storage
C++ Interlude 7
The Standard Template Library
Appendix A
Review of C++ Fundamentals
Appendix B
Important Themes in Programming
Appendix C
The Unied Modeling Language
Appendix D
The Software Life Cycle
Appendix E
Mathematical Induction
Appendix F
Algorithm Verication
Appendix G
Files
Appendix H
C++ Header Files and Standard Functions
Appendix I
C++ Documentation Systems
Appendix J
ASCII Character Codes
Appendix K
C++ for Java Programmers
Appendix L
C++ for Python Programmers
Index
Glossary
Answers to Checkpoint Questions

Brief Table of Contents

Organization

v
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

New to this Edition

Whats New?

his edition of Walls and Mirrors is a signicant revision of the previous edition, yet remains committed to a
pedagogical approach that makes the material accessible to students at the introductory level. Although
everything looks new, you will nd the coverage that you enjoyed in previous editions is still here. At a glance,
the book has morebut shorterchapters, a second color, and new C++ Interludes. Lets examine the details.
Organization. The book begins with a shorter Chapter 1, so that it can focus on the specication of abstract data
types (ADTs). After general discussions of problem solving, good programming practices, and ADTs, we specify a simple ADTthe bag. We dene the bags operations within a C++ template interface in a non-threatening
way. We have moved some sections from the original rst chapter to the appendices.
By introducing the bag as the rst ADT we consider, we make the difcult topic of linked data more accessible to students. Adding or removing the rst node in a chain of linked nodes is the easiest task, and these simple
manipulations are the ones we need to use for a linked implementation of the bag. The next ADT that we consider is the stack, a more useful data container that has the same simple chain in one of its denitions. Moreover,
many students are already familiar with stacks. Later, the treatment of lists looks at the more involved operations
of adding and removing a node that lies between existing nodes of a chain.
The rest of the coverage will be familiar to previous users of Walls and Mirrors but often you will nd ADTs
presented in two chapters rather than one. These chapters separate the discussions of specication and implementation. We will describe each chapter later in this preface. To summarize, this organization

Replaces Chapter 1 with an introduction to ADTs and template interfaces using the ADT bag.
Provides a more focused introduction to array-based implementations and link-based implementations
using the ADT bag.

Makes the topic of linked data more accessible to students by discussing it progressively as we introduce
the ADTs bag, stack, and list.

Places greater emphasis on data abstraction as a problem solving tool.


Enhances the separation between specication and implementation of basic ADTs by placing them in
successive chapters.

Species ADTs informally at rst, then in UML, and ultimately in C++ template interfaces.
Demonstrates safe and secure programming practices in completely revised code that adheres to the
C++11 standard.

Covers the ADT heap in its own chapter.


Reorganizes the coverage of the ADT dictionary (formerly called the ADT table) into two chapters.
C++ Interludes. The introduction of C++ classes and other aspects of C++ that we need for our presentation
and were previously covered in Chapters 3, 4, and 8 of the previous edition are now featured in C++ Interludes.
Seven of these mini-chapters appear throughout the book to cover relevant C++ topics as we need them. Note
that these interludes separate the details of C++ from the discussion of data structures.
VideoNotes. Online tutorials are a Pearson feature that provides visual and audio support to the presentation
given throughout the book. They offer students another way to recap and reinforce key concepts. VideoNotes
allow for self-paced instruction with easy navigation, including the ability to select, play, rewind, fast-forward,
and stop within each video. Unique VideoNote icons appear throughout this book whenever a video is available
for a particular concept or problem. A detailed list of the 49 VideoNotes for this text and their associated locations in the book can be found on page xxiii. VideoNotes are free with the purchase of a new textbook. To purchase access to VideoNotes, please go to
www.pearsonhighered.com/carrano

vi
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Adds a second color to enhance the effectiveness of the illustrations, distinguish pseudocode from C++
code, and provide visual interest.

Includes Notes and Programming Tips to emphasize key material and offer programming advice.
Distinguishes major pieces of code in a new Listing element.
Replaces the self-test exercises at the ends of chapters with Checkpoint Questions placed throughout the
chapters.

Numbers sections and subsections for easy reference.


Includes transition guides from Python to C++ and Java to C++.

New to this Edition

Other features. Walls and Mirrors now has many new features that enhance its usefulness to both readers and
instructors. This edition

vii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Pedagogical Elements

Features to Enhance Learning

The pedagogical features and organization of this book were carefully designed to facilitate learning and to
allow instructors to tailor the material easily to a particular course. These features help students not only during
their rst reading of the material, but also during subsequent review.

Notes Important ideas are presented or summarized in highlighted paragraphs and are meant to be read
in line with the surrounding text.
Programming Tips Suggestions to improve or facilitate programming are featured as soon as they
become relevant.
Examples Numerous examples illuminate new concepts.

CHECK POINT

VideoNote

Checkpoint Questions Questions are posed throughout each chapter, integrated within the text, that
reinforce the concept just presented. These checkpoint questions help readers to understand the
material, since answering them requires pause and reection. Solutions to these questions are provided
online.
VideoNotes Online tutorials provide additional instruction in a more dynamic form than a static
textbook.
Margin Notes Brief phrases in the margins help you review material or locate particular content.
Chapter Summaries Each chapter ends with a list of key ideas that summarize what was presented.
Glossary of Terms A glossary of all terms introduced in this book is available online.
Exercises and Programming Projects Further practice is available by solving the exercises and programming projects at the end of each chapter. Unfortunately, we cannot give readers the answers to
these exercises and programming projects, even if they are not enrolled in a class. Only instructors who
adopt the book can receive selected answers from the publisher. For help with these exercises and
projects, you will have to contact your instructor.

viii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

The following items are available on the publishers website at


www.pearsonhighered.com/carrano

C++ code as it appears in the book


A link to any misprints that have been discovered since the book was published
Links to additional online content, which is described next

Instructor Resources

Resources

Accessing Instructor and Student Resource Materials

The following protected material is available to instructors who adopt this book by logging onto Pearsons Instructor Resource Center, accessible from
www.pearsonhighered.com/carrano

PowerPoint lecture slides


Test bank
Instructor solutions manual
Figures from the book

Additionally, instructors can access the books Companion Website for the following online premium content,
also accessible from
www.pearsonhighered.com/carrano

Instructional VideoNotes
Answers to the Checkpoint Questions
A glossary of terms
Please contact your Pearson sales representative for an instructor access code. Contact information is available
at www.pearsonhighered.com/replocator.

Student Resources
The following material is available to students by logging onto the books Companion Website accessible from

www.pearsonhighered.com/carrano:

Instructional VideoNotes
Answers to the Checkpoint Questions
A glossary of terms
Students must use the access card located in the front of the book to register for and then enter the Companion
Website. Students without an access code can purchase access from the Companion Website by following the
instructions listed there.

ix
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Detailed Content Description

Chapter Overview

Readers of this book should have completed a programming course, preferably in C++. Appendix A covers

the essentials of C++ that we assume readers will know. You can use this appendix as a review or as the basis for
making the transition to C++ from another programming language. Note that Appendices K and L offer some
help for those who are transitioning from Java or Python, respectively.

Chapters 1 through 5: Chapter 1 introduces object-oriented concepts and focuses on the specication of ab-

stract data types (ADTs). Our ADTs now store data whose data type is chosen by the client. To accomplish this,
each specication of an ADT includes a C++ template interface. As an example, Chapter 1 introduces the ADT
bag. Much of the software engineering material that was in Chapter 1 is now in the appendices.
Next is C++ Interlude 1, which presents C++ classes. It gives more details about template interfaceslike
the one presented in Chapter 1and shows how to use inheritance to dene a class derived from an interface.
As it did in earlier editions, Chapter 2 introduces recursion, and Chapter 5 develops it as a problemsolving tool. Recursion is revisited often throughout the book.
We clearly separate the specication, use, and implementation of the bag by dividing the material across
several chapters. For example, Chapter 1 species the bag and provides several examples of its use. Chapter
3 covers implementations that use arrays. Just before Chapter 4 introduces chains of linked nodes and
uses one in the denition of a class of bags, C++ Interlude 2 covers pointers, polymorphism, and dynamic
memory allocation. Both Chapters 3 and 4 include recursion in their presentation.
In a similar fashion, we separate specication from implementation throughout most of the book
when we discuss various other ADTs. You can choose to cover the chapters that specify and use the ADTs
and then later cover the chapters that implement them. Or you can cover the chapters as they appear, implementing each ADT right after studying its specication and use. A list of chapter prerequisites appears
later in this preface to help you plan your path through the book.
Chapter 3 does more than simply implement the ADT bag. It shows how to approach the implementation of a class by initially focusing on core methods. When dening a class, it is often useful to implement
and test these core methods rst and to leave denitions of the other methods for later. Chapter 4 follows
this approach in its development of a link-based implementation of the ADT bag.
Chapters 6 and 7: Chapter 6 discusses stacks, giving examples of their use, and Chapter 7 implements
the stack using an array and then again using a chain. Between these chapters is C++ Interlude 3, which
discusses C++ exceptions. Chapter 7 then shows how to use an exception in the implementation of the
ADT stack, when a client violates a methods precondition.
Chapters 8 and 9: The next two chapters introduce the ADT list. We discuss this container abstractly and
then implement it by using an array and then a chain of linked nodes. Once again, we use exceptions to
enforce method preconditions.
Chapters 10 and 11: Chapter 10 introduces the complexity of algorithms, a topic that we integrate into
future chapters. Chapter 11 discusses various sorting techniques and their relative complexities. We consider both iterative and recursive versions of these algorithms.
Chapter 12: Chapter 12 introduces the sorted list, looking at a linked implementation and its efciency.
We then talk about the relationship between a list and a sorted list and show how to use the list as a base
class for the sorted list. Note that Chapter 12 is preceded by C++ Interlude 4 that discusses class relationships and the various ways a class can be reused. Chapter 12 puts that discussion into immediate use.
Chapters 13 and 14: Chapter 13 presents the ADTs queue and priority queue, along with some uses of
these containers. In doing so, we give an example of simulation that uses both ADTs, and nally summarize the difference between position oriented and value oriented ADTs. Chapter 14 implements the queue,
and introduces tail pointers, circularly linked chains, and circular arrays. We offer an implementation of a
priority queue by using a sorted list, but note that a better approach will come later when we introduce the
ADT heap.

x
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

ators and friend access. We overload operators when we dene classes of trees in this group of chapters.
Chapter 15 discusses treesbinary, binary search, and generaland their possible uses. Chapter 16 considers implementations of these trees, and briey introduces the tree sort. C++ Interlude 6 presents iterators in the context of a list. Chapter 17 introduces the ADT heap and shows how to implement it by using
an array. We then use a heap to implement the priority queue and to sort an array.
Chapter 18: This chapter covers the specication and use of the ADT dictionary (formerly called the
table in the previous edition). We look at implementations of the dictionary that use an array or a binary
search tree. We then introduce hashing and use it as a dictionary implementation.
Chapter 19: Chapter 19 introduces balanced search trees. Included in this chapter are the 2-3, 2-4, and redblack trees, as well as AVL trees. These trees are considered as implementations of the ADT dictionary.
Chapter 20: Next, we discuss graphs, suggest two ways to implement them, and look at several applications.
Chapter 21: This last chapter considers data storage in external direct access les. Merge sort is modied
to sort such data, and external hashing and B-tree indexes are used to search it. These searching algorithms
are generalizations of the internal hashing schemes and 2-3 trees already developed. Finally, C++ Interlude 7 ends the main presentation by discussing the containers and algorithms available in the C++
Standard Template Library (STL).
Appendices A through L: The appendices provide supplemental information. As we mentioned earlier,
Appendix A reviews C++ up to but not including classes. Appendices B, C, D, and F contain sections that
were in Chapter 1 of the previous edition, namely important aspects of programming, the Unied Modeling Language (UML), the software life cycle, and algorithm verication. Appendix E covers mathematical induction, and Appendix G covers input and output with external les. Appendix H provides a list of
C++ header les and standard functions, and Appendix I considers the javadoc commenting style and
denes the tags that we use in this book. Appendix J is simply a chart of the ASCII character codes. Finally, Appendices K and L are brief transition guides to C++ for those who know Java or Python, respectively.

Detailed Content Description

Chapters 15 through 17: Before we begin the next chapter, C++ Interlude 5 introduces overloaded oper-

xi
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Acknowledgements

Acknowledgements

This book evolved from the original Intermediate Problem Solving and Data Structures: Walls and Mirrors by

Paul Helman and Robert Veroff (1986 by The Benjamin/Cummings Publishing Company, Inc.). Professors
Helman and Veroff introduced two powerful analogies, walls and mirrors, that have made it easier for us to
teachand to learncomputer science. This work builds on their organizational framework and overall perspective and includes some technical and textual content, examples, gures, and exercises derived from the
original work.
Our sincere appreciation and thanks go to the following reviewers for carefully reading the previous edition
and making candid comments and suggestions that greatly improved this edition:
Andrew DannerSwarthmore College
Karla S. FantPortland State University
Max Fomitchev-ZamilovPenn State University
Mark Van GorpJohnson County Community College
Sarah GothardWright State University
Ranette H. HalversonMidwestern State University
Shih-Hsi LiuCalifornia State University
Jie Hu MeichsnerSt. Cloud State University
Douglas NiehausUniversity of Kansas
Daniel NohlBenedictine University
Nouhad J. RizkUniversity of Houston
Garth O. SorensonSnow College
Xiaohui YuanUniversity of North Texas
Chao ZhaoCameron University

Special thanks go to our support team at Pearson Education during the lengthy process of revising this
book: Tracy Johnson, Carole Snyder, Bob Engelhardt, and Jeff Holcomb. Our copy editor, Rebecca Pepper, ensured that our presentation is clear, correct, and grammatical. And Rose Kernan of Nesbitt Graphics directed the
production of the book.
The previous edition was greatly improved by the special care taken by Steven J. Holtz, who teaches at the
University of Minnesota Duluth. Paul Nagin and Janet Prichard provided valuable material for earlier editions
of this book. Their contributions endure in this edition.
Numerous other people provided input for the previous editions of Walls and Mirrors at various stages of its
development. All of their comments were useful and greatly appreciated. In alphabetical order, they are Karl
Abrahamson, Stephen Alberg, Ronald Alferez, Vicki Allan, Jihad Almahayni, James Ames, Claude W. Anderson,
Andrew Azzinaro, Tony Baiching, Don Bailey, N. Dwight Barnette, Jack Beidler, Wolfgang W. Bein, Sto Bell,
David Berard, Brian Bershad, John Black, Richard Botting, Woln Brumley, Daryl Carr, Philip Carrigan,
Stephen Clamage, Michael Clancy, David Clayton, Michael Cleron, Chris Constantino, Shaun Cooper, Sarp
Arda Coskun, Charles Denault, Vincent J. DiPippo, Suzanne Dorney, Colleen Dunn, Carl Eckberg, Sebastian
Elbaum, Matthew Evett, Karla Steinbrugge Fant, Caroline Fell, Jean Foltz, Mike Fulford, Susan Gauch, Martin
Granier, Sr., Marguerite Hafen, Randy Hale, George Hamer, Judy Hankins, Jean Harnett, Andrew Hayden,
Michael Hayden, Sarah Hayden, Lisa Hellerstein, Lasse Hellvig, Karsten Henckell, Lesly Hershman, Mary Lou
Hines, Michael Hirsch, Jack Hodges, Larry M. Holt, Stephanie Horoschak, Lily Hou, John Hubbard, Tom Irdy,
Kris Jensen, Thomas Judson, Edwin J. Kay, Laura Kenney, Roger King, Ladislav Kohout, Jim LaBonte, Jean
Lake, Janusz Laski, Elaine Lavallee, Sally Lawrence, Cathie LeBlanc, Greg Lee, Urban LeJeune, Matt Licklider,
Adam Lindstrom, John M. Linebarger, Marilyn Lloyd, Ken Lord, Paul Luker, Ethan Mallove, Manisha Mande,
Pierre-Arnoul de Marneffe, John Marsaglia, Tim Martin, Jane Wallace Mayo, Mark McCormick, Dan
McCracken, Vivian McDougal, Shirley McGuire, Sue Medeiros, Waleed Meleis, Carol Melville, Edalin
Michael, James R. Miller, Jim Miller, Guy Mills, Rameen Mohammadi, Cleve Moler, Narayan Murthy, David
xii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Thank you all.


F. M. C.
T. H.

Acknowledgements

Naff, Paul Nagin, Abhaya Nayak, Rayno Niemi, Debbie Noonan, John ODonnell, Andrew Oldroyd, Larry
Olsen, Raymond L. Paden, Roy Pargas, Brenda C. Parker, Thaddeus F. Pawlicki, Keith Pierce, Gary Pollock,
Albert Prichard, Lucasz Pruski, George B. Purdy, David Radford, Bina Ramamanthy, Steve Ratering, Hal
Records, Stuart Regis, Mateen Rizki, J. D. Robertson, Daniel Rosenkrantz, Robert A. Rossi, Jerry Roth, John
Rowe, Michael E. Rupp, Sharon Salveter, Charles Saxon, Chandra Sekharan, Linda Shapiro, Yujian Sheng,
Mary Shields, Ren-Ben Shiu, Dmitri Slobodin, Ronnie Smith, Carl Spicola, Richard Snodgrass, Neil Snyder,
Ken Sousa, Chris Spannabel, Paul Spirakis, Clinton Staley, Matt Stallman, Mark Stehlick, Benjamin Schomp,
Harriet Taylor, David Teague, Virginia Teller, David Tetreault, Hans-Joerg Tiede, Lindsey Triebel, Dwight
Tuinista, John Turner, Karen Van Houten, Robert Vincent, Susan Wallace, James E. Warren, Xiaoqiao Wei,
Joyce Wells, Jerry Weltman, Nancy Wiegand, Alicia Williams, Howard Williams, Brad Wilson, James Wirth,
Wally Wood, Kathie Yerion, Salih Yurttas, Wu Yusong, Rick Zaccone, and Alan Zaring.
Finally, we thank our families and friendsDoug, Ted, Vandee, Nancy, Sue, Tom, Joanne, Tita, Bobby,
Lorraine, and Margefor giving us lives away from computers.

xiii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Table of Contents

Contents
Chapter 1

C++ Interlude 1

Chapter 2

Data Abstraction: The Walls

1.1 Object-Oriented Concepts


1.1.1 Object-Oriented Analysis and Design
1.1.2 Aspects of an Object-Oriented Solution
1.2 Achieving a Better Solution
1.2.1 Cohesion
1.2.2 Coupling
1.3 Specications
1.3.1 Operation Contracts
1.3.2 Unusual Conditions
1.3.3 Abstraction
1.3.4 Information Hiding
1.3.5 Minimal and Complete Interfaces
1.4 Abstract Data Types
1.4.1 Designing an ADT
1.4.2 ADTs That Suggest Other ADTs
1.5 The ADT Bag
1.5.1 Identifying Behaviors
1.5.2 Specifying Data and Operations
1.5.3 An Interface Template for the ADT
1.5.4 Using the ADT Bag

2
2
3
4
4
5
6
6
8
8
9
10
11
14
16
17
18
19
22
24

C++ Classes

31

Recursion: The Mirrors

47

C1.1 A Problem to Solve


C1.1.1 Private Data Fields
C1.1.2 Constructors and Destructors
C1.1.3 Methods
C1.1.4 Preventing Compiler Errors
C1.2 Implementing a Solution
C1.3 Templates
C1.4 Inheritance
C1.4.1 Base Classes and Derived Classes
C1.4.2 Overriding Base-Class Methods
C1.5 Virtual Methods and Abstract Classes
C1.5.1 Virtual Methods
C1.5.2 Abstract Classes

2.1 Recursive Solutions


2.2 Recursion That Returns a Value
2.2.1 A Recursive Valued Function: The Factorial of n
2.2.2 The Box Trace
2.3 Recursion That Performs an Action
2.3 .1 A Recursive Void Function: Writing a String Backward
2.4 Recursion with Arrays
2.4.1 Writing an Arrays Entries in Backward Order
2.4.2 The Binary Search
2.4.3 Finding the Largest Value in an Array
2.4.4 Finding the kth Smallest Value of an Array

xiv
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

32
33
33
34
35
36
37
40
40
42
44
44
45

48
50
50
54
57
57
67
67
68
72
72

76
76
79
79
82
83
85

Array-Based Implementations

95

3.1 The Approach


3.1.1 Core Methods
3.1.2 Using Fixed-Size Arrays
3.2 An Array-Based Implementation of the ADT Bag
3.2.1 The Header File
3.2.2 Dening the Core Methods
3.2.3 Testing the Core Methods
3.2.4 Implementing More Methods
3.2.5 Methods That Remove Entries
3.2.6 Testing
3.3 Using Recursion in the Implementation
3.3.1 The Method getIndexOf
3.3.2 The Method getFrequencyOf

96
97
98
98
99
100
103
105
107
110
112
112
113

Pointers, Polymorphism, and Memory Allocation

117

Chapter 4

Link-Based Implementations

133

Chapter 5

Recursion as a Problem-Solving Technique

159

C++ Interlude 2

C2.1 Memory Allocation for Variables and Early Binding of Methods


C2.2 A Problem to Solve
C2.3 Pointers and the Programs Free Store
C2.3.1 Deallocating Memory
C2.3.2 Avoiding Memory Leaks
C2.3.3 Avoiding Dangling Pointers
C2.4 Virtual Methods and Polymorphism
C2.5 Dynamic Allocation of Arrays
C2.5.1 A Resizable Array-Based Bag
4.1 Preliminaries
4.1.1 The Class Node
4.2 A Link-Based Implementation of the ADT Bag
4.2.1 The Header File
4.2.2 Dening the Core Methods
4.2.3 Implementing More Methods
4.3 Using Recursion in Link-Based Implementations
4.3.1 Recursive Denitions of Methods in LinkedBag
4.4 Testing Multiple ADT Implementations
4.5 Comparing Array-Based and Link-Based Implementations
5.1 Dening Languages
5.1.1 The Basics of Grammars
5.1.2 Two Simple Languages
5.2 Algebraic Expressions
5.2.1 Kinds of Algebraic Expressions

Table of Contents

Chapter 3

2.5 Organizing Data


2.5.1 The Towers of Hanoi
2.6 More Examples
2.6.1 The Fibonacci Sequence (Multiplying Rabbits)
2.6.2 Organizing a Parade
2.6.3 Choosing k Out of n Things
2.7 Recursion and Efciency

118
118
120
122
123
127
128
130
131
134
136
137
138
139
143
148
148
150
153
160
160
162
164
164
xv

2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Table of Contents

5.2.2 Prex Expressions


5.2.3 Postx Expressions
5.2.4 Fully Parenthesized Expressions
5.3 Backtracking
5.3.1 Searching for an Airline Route
5.3.2 The Eight Queens Problem
5.4 The Relationship Between Recursion and Mathematical Induction
5.4.1 The Correctness of the Recursive Factorial Function
5.4.2 The Cost of Towers of Hanoi

166
170
171
172
172
177
183
183
184

Stacks

193

Exceptions

227

Stack Implementations

241

Chapter 8

Lists

253

Chapter 9

List Implementations

265

Chapter 6

C++ Interlude 3

Chapter 7

6.1 The Abstract Data Type Stack


6.1.1 Developing an ADT During the Design of a Solution
6.1.2 Specications for the ADT Stack
6.2 Simple Uses of a Stack
6.2.1 Checking for Balanced Braces
6.2.2 Recognizing Strings in a Language
6.3 Using Stacks with Algebraic Expressions
6.3.1 Evaluating Postx Expressions
6.3.2 Converting Inx Expressions to Equivalent Postx Expressions
6.4 Using a Stack to Search a Flight Map
6.5 The Relationship Between Stacks and Recursion
C3.1 Background
C3.1.1 A Problem to Solve
C3.2 Assertions
C3.3 Throwing Exceptions
C3.4 Handling Exceptions
C3.4.1 Multiple catch Blocks
C3.4.2 Uncaught Exceptions
C3.5 Programmer-Dened Exception Classes
7.1 An Array-Based Implementation
7.2 A Link-Based implementation
7.3 Implementations That Use Exceptions
8.1 Specifying the ADT List
8.2 Using the List Operations
8.3 An Interface Template for the ADT List
9.1 An Array-Based Implementation of the ADT List
9.1.1 The Header File
9.1.2 The Implementation File
9.2 A Link-Based Implementation of the ADT List
9.2.1 The Header File
9.2.2 The Implementation File
9.2.3 Using Recursion in LinkedList Methods
9.3 Comparing Implementations

xvi
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

194
194
196
201
201
203
205
205
206
210
216

228
228
229
230
233
235
236
239
242
245
249
254
259
261

266
266
268
272
272
274
281
285

289

Chapter 11 Sorting Algorithms and Their Efciency

305

10.1 What Is a Good Solution?


10.2 Measuring the Efciency of Algorithms
10.2.1 The Execution Time of Algorithms
10.2.2 Algorithm Growth Rates
10.2.3 Analysis and Big O Notation
10.2.4 Keeping Your Perspective
10.2.5 The Efciency of Searching Algorithms
11.1 Basic Sorting Algorithms
11.1.1 The Selection Sort
11.1.2 The Bubble Sort
11.1.3 The Insertion Sort
11.2 Faster Sorting Algorithms
11.2.1 The Merge Sort
11.2.2 The Quick Sort
11.2.3 The Radix Sort
11.3 A Comparison of Sorting Algorithms

C++ Interlude 4 Class Relationships and Reuse

C4.1 Inheritance Revisited


C4.1.1 Public, Private, and Protected Sections of a Class
C4.1.2 Public, Private, and Protected Inheritance
C4.1.3 Is-a and As-a Relationships
C4.2 Containment: Has-a Relationships
C4.3 Abstract Base Classes Revisited

290
291
292
293
294
298
300
306
306
309
311
313
313
318
327
329

333

333
338
340
340
342
343

Chapter 12 Sorted Lists and Their Implementations

347

Chapter 13 Queues and Priority Queues

373

12.1 Specifying the ADT Sorted List


12.1.1 An Interface Template for the ADT Sorted List
12.1.2 Using the Sorted List Operations
12.2 A Link-Based Implementation
12.2.1 The Header File
12.2.2 The Implementation File
12.2.3 The Efciency of the Link-Based Implementation
12.3 Implementations That Use the ADT List
12.3.1 Containment
12.3.2 Public Inheritance
12.3.3 Private Inheritance
13.1 The ADT Queue
13.2 Simple Applications of the ADT Queue
13.2.1 Reading a String of Characters
13.2.2 Recognizing Palindromes
13.3 The ADT Priority Queue
13.3.1 Tracking Your Assignments
13.4 Application: Simulation
13.5 Position-Oriented and Value-Oriented ADTs

Table of Contents

Chapter 10 Algorithm Efciency

348
350
351
352
353
354
357
357
357
362
366

374
377
377
377
379
380
381
389

xvii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Table of Contents

Chapter 14 Queue Implementations

14.1 Implementations of the ADT Queue


14.1.1 An Implementation That Uses the ADT List
14.1.2 A Link-Based Implementation
14.1.3 An Array-Based Implementation
14.1.4 Comparing Implementations
14.2 An Implementation of the ADT Priority Queue

C++ Interlude 5 Overloaded Operators and Friend Access


C5.1 Overloaded Operators
C5.1.1 Overloading = for Assignment
C5.1.2 Overloading + for Concatenation
C5.2 Friend Access and Overloading

397

397
398
400
405
410
411

415

415
417
419
421

Chapter 15 Trees

425

Chapter 16 Tree Implementations

455

15.1 Terminology
15.1.1 Kinds of Trees
15.1.2 The Height of Trees
15.1.3 Full, Complete, and Balanced Binary Trees
15.1.4 The Maximum and Minimum Heights of a Binary Tree
15.2 The ADT Binary Tree
15.2.1 Traversals of a Binary Tree
15.2.2 Binary Tree Operations
15.2.3 An Interface Template for the ADT Binary Tree
15.3 The ADT Binary Search Tree
15.3.1 Binary Search Tree Operations
15.3.2 Searching a Binary Search Tree
15.3.3 Creating a Binary Search Tree
15.3.4 Traversals of a Binary Search Tree
15.3.5 The Efciency of Binary Search Tree Operations

16.1 The Nodes in a Binary Tree


16.1.1 An Array-Based Representation
16.1.2 A Link-Based Representation
16.2 A Link-Based Implementation of the ADT Binary Tree
16.2.1 The Header File
16.2.2 The Implementation
16.3 A Link-Based Implementation of the ADT Binary Search Tree
16.3.1 Algorithms for the ADT Binary Search Tree Operations
16.3.2 The Class BinarySearchTree
16.4 Saving a Binary Search Tree in a File
16.5 Tree Sort
16.6 General Trees

C++ Interlude 6 Iterators

C6.1 Iterators
C6.1.1 Common Iterator Operations
C6.1.2 Using Iterator Operations
C6.1.3 Implementing an Iterator
C6.2 Advanced Iterator Functionality

xviii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

426
428
430
431
433
435
436
438
441
442
443
445
446
447
448

456
456
458
459
459
462
471
471
481
483
486
487

493

493
494
496
497
499

503

Chapter 18 Dictionaries and Their Implementations

525

Chapter 19 Balanced Search Trees

567

Chapter 20 Graphs

603

17.1 The ADT Heap


17.2 An Array-Based Implementation of a Heap
17.2.1 Algorithms for the Array-Based Heap Operations
17.2.2 The Implementation
17.3 A Heap Implementation of the ADT Priority Queue
17.4 Heap Sort
18.1 The ADT Dictionary
18.1.1 An Interface for the ADT Dictionary
18.2 Possible Implementations
18.2.1 A Sorted Array-Based Implementation of the ADT Dictionary
18.2.2 A Binary Search Tree Implementation of the ADT Dictionary
18.3 Selecting an Implementation
18.3.1 Four Scenarios
18.4 Hashing
18.4.1 Hash Functions
18.4.2 Resolving Collisions
18.4.3 The Efciency of Hashing
18.4.4 What Constitutes a Good Hash Function?
18.4.5 Dictionary Traversal: An Inefcient Operation Under Hashing
18.4.6 Using Hashing and Separate Chaining to Implement the ADT Dictionary
19.1 Balanced Search Trees
19.2 2-3 Trees
19.2.1 Traversing a 2-3 Tree
19.2.2 Searching a 2-3 Tree
19.2.3 Inserting Data into a 2-3 Tree
19.2.4 Removing Data from a 2-3 Tree
19.3 2-3-4 Trees
19.3.1 Searching and Traversing a 2-3-4 Tree
19.3.2 Inserting Data into a 2-3-4 Tree
19.3.3 Removing Data from a 2-3-4 Tree
19.4 Red-Black Trees
19.4.1 Searching and Traversing a Red-Black Tree
19.4.2 Inserting into and Removing from a Red-Black Tree
19.5 AVL Trees
20.1 Terminology
20.2 Graphs as ADTs
20.2.1 Implementing Graphs
20.3 Graph Traversals
20.3.1 Depth-First Search
20.3.2 Breadth-First Search
20.4 Applications of Graphs
20.4.1 Topological Sorting

503
506
508
512
516
519

526
530
531
534
536
538
539
544
547
549
554
557
559
559

Table of Contents

Chapter 17 Heaps

568
569
572
572
575
579
585
587
587
591
592
594
594
597
604
606
608
611
611
613
615
615

xix
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Table of Contents

20.4.2
20.4.3
20.4.4
20.4.5
20.4.6

Spanning Trees
Minimum Spanning Trees
Shortest Paths
Circuits
Some Difcult Problems

Chapter 21 Processing Data in External Storage


21.1 A Look at External Storage
21.2 Sorting Data in an External File
21.3 External Tables
21.3.1 Indexing an External File
21.3.2 External Hashing
21.3.3 B-Trees
21.3.4 Traversals
21.3.5 Multiple Indexing

C++ Interlude 7 The Standard Template Library


C7.1 STL Containers
C7.1.1 Container Adaptors
C7.1.2 Sequence Containers
C7.1.3 Associative Containers
C7.2 STL Algorithms

618
621
624
627
629

637

638
640
646
648
651
654
662
664

671

671
673
674
678
682

Appendix A

Review of C++ Fundamentals

685

Appendix B

Important Themes in Programming

721

Appendix C

The Unied Modeling Language

741

Appendix D

The Software Life Cycle

749

Appendix E

Mathematical Induction

755

Appendix F

Algorithm Verication

759

Appendix G

Files

763

Appendix H

C++ Header Files and Standard Functions

773

Appendix I

C++ Documentation Systems

777

Appendix J

ASCII Character Codes

779

Appendix K

C++ for Java Programmers

781

Appendix L

C++ for Python Programmers

789

Index

797

Glossary

Available online

Answers to Checkpoint Questions

Available online

xx
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Each chapter, interlude, and appendix assumes that the reader has studied certain previous material. This list

indicates those prerequisites. Numbers represent chapter numbers, and letters reference appendices. The notation Ix represents C++ Interlude x. Underlined prerequisites indicate an incidental or a partial dependence. You
can use this information to plan a path through the book.
Prerequisites
Chapter 1

Data Abstraction: The Walls

A, B, C

C++ Interlude 1

C++ Classes

A, 1

Chapter 2

Recursion: The Mirrors

A, B, C

Chapter 3

Array-Based Implementations

A, 1, I1, 2

C++ Interlude 2

Pointers, Polymorphism, and Memory Allocation

Chapter 4

Link-Based Implementations

1, I1, 2, 3, I2

Chapter 5

Recursion as a Problem-Solving Technique

Chapter 6

Stacks

1, I1

C++ Interlude 3

Exceptions

I1

Chapter 7

Stack Implementations

3, I2, 4, 6, I3

Chapter 8

Lists

1, I1

Chapter 9

List Implementations

3, I2, 4, I3, 8

Chapter 10

Algorithm Efciency

1, 2, 4, 9

Chapter 11

Sorting Algorithms and Their Efciency

2, 5, 10

C++ Interlude 4

Class Relationships and Reuse

1, I1, I2, 6, 8

Chapter 12

Sorted Lists and Their Implementations

8, 10, I4

Chapter 13

Queues and Priority Queues

6, 8, 12

Chapter 14

Queue Implementations

13

C++ Interlude 5

Overloaded Operators and Friend Access

4, 8, 9

Chapter 15

Trees

2, 4, 5, 6, 8, 10, 13

Chapter 16

Tree Implementations

4, 5, 6, 9, 10, 12, I5, 15

C++ Interlude 6

Iterators

9, I5

Chapter 17

Heaps

13, 15, 16

Chapter 18

Dictionaries and Their Implementations

4, 10, 11, 12, 15, 16

Chapter 19

Balanced Search Trees

15, 16, 18

Chapter 20

Graphs

5, 6, 15

Chapter 21

Processing Data in External Storage

G, 11, 18, 19

C++ Interlude 7

The Standard Template Library

N/A

Appendix A

Review of C++ Fundamentals

Knowledge of a programming language

Chapter Prerequisites

Chapter Prerequisites

xxi
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Chapter Prerequisites

Appendix B

Important Themes in Programming

A, 1

Appendix C

The Unied Modeling Language

I4

Appendix D

The Software Life Cycle

A general knowledge of
software

Appendix E

Mathematical Induction

Ability to prove theorems

Appendix F

Algorithm Verication

Appendix G

Files

Appendix H

C++ Header Files and Standard Functions

N/A

Appendix I

C++ Documentation Systems

N/A

Appendix J

ASCII Character Codes

N/A

Appendix K

C++ for Java Programmers

Java programming

Appendix L

C++ for Python Programmers

Python programming

xxii
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

VideoNote

Chapter 1
C++ Interlude 1
Chapter 2
Chapter 3
C++ Interlude 2

Data Abstraction: The Walls

Object-Oriented Concepts
Designing an ADT

C++ Classes
C++ Classes

Recursion: The Mirrors


Recursion: The Mirrors
Recursion with Arrays

Array-Based Implementations

Core ArrayBag Methods


Other ArrayBag Methods

Pointers, Polymorphism, and Memory Allocation


C++ Memory Allocation

Chapter 4

Link-Based Implementations

Chapter 5

Recursion as a Problem-Solving Technique

Chapter 6

Stacks

C++ Interlude 3
Chapter 7

Linked Chain Concepts


Core LinkedBag Methods
Processing Expressions
Backtracking
The ADT Stack
Using the ADT Stack

Exceptions

C++ Exceptions

Stack Implementations

Overview of ArrayStack
Overview of LinkedStack

Chapter 8

Lists

Chapter 9

List Implementations

The ADT List


Using the ADT List
Overview of ArrayList
Overview of LinkedList

Chapter 10 Algorithm Efciency

Measuring Algorithmic Efciency


Understanding Big O Notation

Chapter 11 Sorting Algorithms and Their Efciency


Basic Sorting Algorithms
Faster Sorting Algorithms

2
14
32
50
67
98
107
120

VideoNotes Directory

VideoNotes Directory

134
137
164
172
194
201
230
242
245
254
259
268
274
291
294
306
313
xxiii

2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

VideoNotes Directory

C++ Interlude 4 Class Relationships and Reuse


C++ Inheritance and Access

Chapter 12 Sorted Lists and Their Implementations


The ADT Sorted List
ADT Sorted List Implementations

Chapter 13 Queues and Priority Queues


The ADT Queue
Using the ADT Queue

Chapter 14 Queue Implementations


Overview of LinkedQueue
Overview of ArrayQueue

C++ Interlude 5 Overloaded Operators and Friend Access


C++ Operator Overloading

Chapter 15 Trees

Tree Concepts
The ADT Binary Search Tree

Chapter 16 Tree Implementations

Representing Tree Nodes


Overview of BinarySearchTree

C++ Interlude 6 Iterators

C++ Iterators

Chapter 17 Heaps

The ADT Heap


Overview of ArrayHeap

Chapter 18 Dictionaries and Their Implementations


The ADT Dictionary
Hashing

Chapter 19 Balanced Search Trees

2-3 Trees
2-3-4 Trees and Red-Black Trees

Chapter 20 Graphs

Graph Concepts
Graph Operations

Chapter 21 Processing Data in External Storage


Sorting File Data
Managing External Data

C++ Interlude 7 The Standard Template Library


C++ Standard Template Library

xxiv
2013 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

338
353
357
374
377
398
405
415
426
442
456
471
493
504
506
526
544
569
585
604
611
640
646
671