Table Of ContentThis page intentionally left blank
i i
“main” — 2011/1/13 — 9:10 — page i — #1
i i
Data Structures and
Algorithms in C++
Second Edition
i i
i i
This page intentionally left blank
i i
“main” — 2011/1/13 — 9:10 — page iii — #3
i i
Data Structures and
Algorithms in C++
Second Edition
Michael T. Goodrich
DepartmentofComputerScience
UniversityofCalifornia, Irvine
Roberto Tamassia
DepartmentofComputerScience
BrownUniversity
David M. Mount
DepartmentofComputerScience
UniversityofMaryland
John Wiley & Sons, Inc.
i i
i i
i i
“main” — 2011/1/13 — 9:10 — page iv — #4
i i
ACQUISITIONSEDITOR BethLangGolub
MARKETINGMANAGER ChrisRuel
EDITORIALASSISTANT ElizabethMills
MEDIAEDITOR ThomasKulesa
SENIORDESIGNER JimO’Shea
CONTENTMANAGER MichelineFrederick
PRODUCTIONEDITOR AmyWeintraub
PHOTOEDITOR SheenaGoldstein
ThisbookwassetinLATEXbytheauthorsandprintedandboundbyMalloyLithographers.
ThecoverwasprintedbyMalloyLithographers.ThecoverimageisfromWutaWutaTjan-
gala,“Emudreaming” c estateoftheartist2009licensedbyAboriginalArtistsAgency.
(cid:13)
JenniferSteele/ArtResource,NY.
Thisbookisprintedonacidfreepaper.
∞
TrademarkAcknowledgments: JavaisatrademarkofSunMicrosystems, Inc. UNIX(cid:13)R is
aregisteredtrademarkintheUnitedStatesandothercountries,licensedthroughX/Open
Company,Ltd. PowerPoint(cid:13)R isatrademarkofMicrosoftCorporation. Allotherproduct
namesmentionedhereinarethetrademarksoftheirrespectiveowners.
Copyright c 2011,JohnWiley&Sons,Inc. Allrightsreserved.
(cid:13)
Nopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmitted
in anyform or by any means, electronic, mechanical, photocopying,recording, scanning
or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States
CopyrightAct,withouteitherthepriorwrittenpermissionofthePublisher,orauthorization
throughpaymentof the appropriateper-copyfee to the CopyrightClearance Center, Inc.
222RosewoodDrive,Danvers,MA01923,(978)750-8400,fax(978)646-8600.
Requests to the Publisherfor permissionshould be addressedto the PermissionsDepart-
ment,JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030,(201)748-6011,fax
(201)748-6008,E-Mail:PERMREQ@WILEY.COM.
Toorderbooksorforcustomerservicepleasecall1-800-CALLWILEY(225-5945).
Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and
understandingformorethan200years,helpingpeoplearoundtheworldmeettheirneeds
andfulfilltheiraspirations.Ourcompanyisbuiltonafoundationofprinciplesthatinclude
responsibility to the communities we serve and where we live and work. In 2008, we
launched a Corporate Citizenship Initiative, a globaleffortto address the environmental,
social, economic, and ethical challenges we face in our business. Among the issues we
are addressing are carbon impact, paper specifications and procurement, ethical conduct
within our business and amongourvendors, and communityand charitable support. For
moreinformation,pleasevisitourwebsite: www.wiley.com/go/citizenship.
LibraryofCongressCataloginginPublicationData
ISBN-13978-0-470-38327-8
PrintedintheUnitedStatesofAmerica
10987654321
i i
i i
i i
“main” — 2011/1/13 — 9:10 — page v — #5
i i
To Karen, Paul,Anna, and Jack
– MichaelT.Goodrich
To Isabel
– RobertoTamassia
ToJeanine
– DavidM. Mount
i i
i i
This page intentionally left blank
i i
“main” — 2011/1/13 — 9:10 — page vii — #7
i i
Preface
This second edition of Data Structures and Algorithms in C++ is designed to pro-
videanintroductiontodatastructuresandalgorithms,includingtheirdesign,analy-
sis,andimplementation. IntermsofcurriculabasedontheIEEE/ACM2001Com-
puting Curriculum, this book is appropriate for use in the courses CS102 (I/O/B
versions),CS103(I/O/Bversions),CS111(Aversion),andCS112(A/I/O/F/Hver-
sions). Wediscussitsuseforsuchcoursesinmoredetaillaterinthispreface.
Themajorchanges inthesecondeditionarethefollowing:
Weaddedmoreexamplesofdatastructureandalgorithm analysis.
•
Weenhanced consistency withtheC++StandardTemplateLibrary(STL).
•
Weincorporated STLdatastructures intomanyofourdatastructures.
•
Weaddedachapteronarrays,linkedlists,anditerators (Chapter3).
•
Weaddedachapteronmemorymanagement andB-trees(Chapter14).
•
Weenhanced the discussion of algorithmic design techniques, like dynamic
•
programming andthegreedymethod.
Wesimplifiedandreorganized thepresentation ofcodefragments.
•
We have introduced STL-style iterators into our container classes, and have
•
presented C++ implementations for these iterators, even for complex struc-
turessuchashashtablesandbinarysearchtrees.
We have modified our priority-queue interface to use STL-style comparator
•
objects.
We expanded and revised exercises, continuing our approach of dividing
•
themintoreinforcement, creativity, andprojectexercises.
Thisbookisrelatedtothefollowingbooks:
M.T. Goodrich and R. Tamassia, Data Structures and Algorithms in Java,
•
John Wiley & Sons, Inc. This book has a similar overall structure to the
present book, but uses Java as the underlying language (with some modest,
butnecessary pedagogical differences requiredbythisapproach).
M.T. Goodrich and R. Tamassia, Algorithm Design: Foundations, Analysis,
•
andInternetExamples,JohnWiley&Sons,Inc. Thisisatextbookforamore
advanced algorithms and data structures course, such as CS210 (T/W/C/S
versions) intheIEEE/ACM2001curriculum.
While this book retains the same pedagogical approach and general structure
as Data Structures and Algorithms in Java, the code fragments have been com-
pletelyredesigned. WehavebeencarefultomakefulluseofC++’scapabilitiesand
design code in a manner that is consistent with modern C++ usage. In particular,
whenever appropriate, wemakeextensive useofC++elements thatarenot partof
Java,includingtheC++StandardTemplateLibrary(STL),C++memoryallocation
vii
i i
i i
i i
“main” — 2011/1/13 — 9:10 — page viii — #8
i i
viii Preface
anddeallocation(andtheassociatedissuesofdestructors),virtualfunctions,stream
inputandoutput,operator overloading, andC++’ssaferun-timecasting.
Use as a Textbook
The design and analysis of efficient data structures has long been recognized as a
vital subject in computing, because the study of data structures is part of the core
ofeverycollegiate computer science andcomputer engineering majorprogram we
are familiar with. Typically, the introductory courses are presented as a two- or
three-course sequence. Elementary data structures are often briefly introduced in
thefirstprogramming course orinanintroduction tocomputer science course and
thisisfollowedbyamorein-depthintroductiontodatastructuresinthecoursesthat
follow after this. Furthermore, thiscourse sequence istypically followed atalater
pointinthecurriculum byamorein-depth studyofdatastructures andalgorithms.
Wefeelthatthecentral roleofdatastructure designandanalysisinthecurriculum
isfully justified, given the importance ofefficient data structures inmost software
systems,includingtheWeb,operatingsystems,databases,compilers,andscientific
simulation systems.
Withtheemergenceoftheobject-orientedparadigmastheframeworkofchoice
forbuildingrobustandreusablesoftware,wehavetriedtotakeaconsistent object-
oriented viewpoint throughout this text. One of the main ideas behind the object-
oriented approach is that data should be presented as being encapsulated with the
methods that access and modify them. That is, rather than simply viewing data
as a collection of bytes and addresses, we think of data objects as instances of an
abstract data type (ADT), which includes a repertoire of methods for performing
operationsondataobjectsofthistype. Likewise,object-orientedsolutionsareoften
organized utilizing common design patterns, which facilitate software reuse and
robustness. Thus, we present each data structure using ADTsand their respective
implementations and we introduce important design patterns as a way to organize
thoseimplementations intoclasses, methods,andobjects.
For most of the ADTs presented in this book, we provide a description of the
public interface in C++. Also, concrete data structures realizing the ADTs are
discussed and we often give concrete C++ classes implementing these interfaces.
WealsogiveC++implementations offundamental algorithms, suchassortingand
graphsearching. Moreover,inadditiontoprovidingtechniquesforusingdatastruc-
turestoimplementADTs,wealsogivesampleapplicationsofdatastructures,such
as HTML tag matching and a simple system to maintain a play list for a digital
audio system. Duetospacelimitations, however, weonlyshow codefragments of
some of the implementations in this book and make additional source code avail-
ableonthecompanionwebsite.
i i
i i