Data Structures Demystified ISBN:0072253592 by Jim Keogh and Ken Davidson McGraw-Hill/Osborne © 2004 Whether you are an entry-level or seasoned designer or programmer, learn all about data structures in this easy-to-understand, selfteaching guide that can be directly applied to any programming language Table of Contents Data Structures Demystified Introduction Memory, Abstract Data Types, and Chapter 1 Addresses Chapter 2 - The Point About Variables and Pointers Chapter 3 - What Is an Array? Chapter 4 - Stacks Using an Array Chapter 5 - Queues Using an Array Chapter 6 - What Is a Linked List? Chapter 7 - Stacks Using Linked Lists Chapter 8 - Queues Using Linked Lists Stacks and Queues: Insert, Delete, Peek, Chapter 9 Find Chapter 10 - What Is a Tree? Chapter 11 - What Is a Hashtable? Final Exam Index List of Figures List of Tables Back Cover If you’ve been searching for that quick, easy-tounderstand guide to walk you through data structures, look no further Data Structures Demystified is all these things and more Whether you’re trying to program stacks and linked lists or figure out hashtables, here you’ll find step-by-step instructions to get the job done fast No longer will you have to wade through thick, dry, academic tomes, heavy on technical language and information you don’t need In Data Structures Demystified, each chapter starts off with an example from everyday life to demonstrate upcoming concepts, making this a totally accessible read The authors go a step further and offer examples at the end of the chapter illustrating what you’ve just learned in Java and C++ This one-of-a-kind self-teaching text offers: An easy way to understand data structures A quiz at the end of each chapter A final exam at the end of the book No unnecessary technical jargon A time-saving approach About the Authors Jim Keogh is a member of the faculty of Columbia University, where he teaches courses on Java Application Development, and is a member of the Java Community Process Program He developed the first ecommerce track at Columbia and became its first chairperson Jim spent more than a decade developing advanced systems for major Wall Street firms and is also the author of several best-selling computer books Ken Davidson is a member of the faculty of Columbia University, where he teaches courses on Java Application Development Ken has spent more than a decade developing advanced systems for major international firms Data Structures Demystified James Keogh & Ken Davidson McGraw-Hill/Osborne New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto McGraw-Hill/Osborne 2100 Powell Street, 10th Floor Emeryville, California 94608 U.S.A To arrange bulk purchase discounts for sales promotions, premiums, or fund-raisers, please contact McGraw-Hill/Osborne at the above address For information on translations or book distributors outside the U.S.A., please see the International Contact Information page immediately following the index of this book Data Structures Demystified Copyright © 2004 by The McGraw-Hill Companies All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication 1234567890 FGR FGR 01987654 ISBN 0-07-225359-2 Publisher Brandon A Nordin Vice President & Associate Publisher Scott Rogers Editorial Director Wendy Rinaldi Project Editor Jennifer Malnick Acquisitions Coordinator Athena Honore Technical Editor Jeff Kent Copy Editor Sally Engelfried Proofreader Linda Medoff Indexer Claire Splan Composition Jean Butterfield, Tara A Davis Illustrators Kathleen Edwards, Melinda Lytle Cover Series Design Margaret Webster-Shapiro Cover Illustration Lance Lekander This book was composed with Corel VENTURA™ Publisher Information has been obtained by McGraw-Hill/Osborne from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill/Osborne, or others, McGraw-Hill/Osborne does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information This book is dedicated to Anne, Sandy, Joanne, Amber-Leigh Christine, and Graaf, without whose help and support this book couldn’t be written —Jim To Janice, Jack, Alex, and Liz —Ken About the Authors Jim Keogh is a member of the faculty of Columbia University, where he teaches courses on Java Application Development, and is a member of the Java Community Process Program He developed the first ecommerce track at Columbia and became its first chairperson Jim spent more than a decade developing advanced systems for major Wall Street firms and is also the author of several best-selling computer books Ken Davidson is a member of the faculty of Columbia University, where he teaches courses on Java Application Development Ken has spent more than a decade developing advanced systems for major international firms Introduction This book is for everyone who wants to learn basic data structures using C++ and Java without taking a formal course It also serves as a supplemental classroom text For the best results, start at the beginning and go straight through If you are confident about your basic knowledge of how computer memory is allocated and addressed, then skip the first two chapters, but take the quiz at the end of those chapters to see if you are actually ready to jump into data structures If you get 90 percent of the answers correct, you’re ready If you get 75 to 89 percent correct, skim through the text of Chapters 1 and 2 If you get less than 75 percent of the answers correct, then find a quiet place and begin reading Chapters 1 and 2 Doing so will get you in shape to tackle the rest of the chapters on data structures In order to learn data structures, you must have some computer programming skills—computer programming is the language used to create data structures But don’t be intimidated; none of the programming knowledge you need goes beyond basic programming in C++ and Java This book contains a lot of practice quizzes and exam questions, which are similar to the kind of questions used in a data structures course You may and should refer to the chapter texts when taking them When you think you’re ready, take the quiz, write down your answers, and then give your list of answers to a friend Have your friend tell you your score, but not which questions were wrong Stay with one chapter until you pass the quiz You’ll find the answers in Appendix B There is a final exam in Appendix A, at the end of the book, with practical questions drawn from all chapters of this book Take the exam when you have finished all the chapters and have completed all the quizzes A satisfactory score is at least 75 percent correct answers Have a friend tell you your score without letting you know which questions you missed on the exam We recommend that you spend an hour or two each day; expect to complete one chapter each week Don’t rush Take it at a steady pace Take time to absorb the material You’ll complete the course in a few months; then you can use this book as a comprehensive permanent reference Chapter 1: Memory, Abstract Data Types, and Addresses What is the maximum number of tries you’d need to find your name in a list of a million names? A million? No, not even close The answer is 20— if you structure the list to make it easy to search and if you search the structure with an efficient searching technique Searching lists is one of the many ways data structures help you manipulate data that is stored in your computer’s memory However, before you can understand how to use data structures, you need to have a firm grip on how computer memory works In this chapter, you’ll explore what computer memory is and why only zeros and ones are stored in memory You’ll also learn what a Java data type is and how to select the best Java data type to reserve memory for data used by your program List of Figures Chapter 1: Memory, Abstract Data Types, and Addresses Figure 1-1: A bus connects the CPU, main memory, persistent storage, and other devices Figure 1-2: A byte abstract data type in Java reserves 8 bits of main memory Figure 1-3: A short abstract data type in Java reserves 16 bits of main memory Figure 1-4: An int abstract data type in Java reserves 32 bits of main memory Figure 1-5: A long abstract data type in Java reserves 64 bits of main memory Figure 1-6: A float abstract data type in Java reserves 32 bits of main memory Figure 1-7: A double abstract data type in Java reserves 64 bits of main memory Figure 1-8: A char abstract data type in Java reserves 16 bits of main memory Figure 1-9: A boolean abstract data type in Java reserves 1 bit of main memory Figure 1-10: The memory address of the first byte is used to reference all bytes reserved for an abstract data type Chapter 2: The Point About Variables and Pointers Figure 2-1: Memory for elements of a structure are placed in sequential memory locations when an instance of the structure is declared Figure 2-2: Memory for attributes of a class are placed in sequential memory locations when an instance of the class is declared Figure 2-3: Memory allocated when two pointers and two variables are declared Figure 2-4: Memory allocated after pointers are assigned memory addresses Figure 2-5: Memory allocated after values are assigned to variables Figure 2-6: Memory allocated after the value of the ptGrade is copied to ptOldGrade Figure 2-7: Memory allocated after the contents of the memory address pointed to by ptGrade is copied to the oldGrade variable Figure 2-8: Memory allocation before incrementing ptStudentNumber1 Figure 2-9: Memory allocation after incrementing ptStudentNumber1 Figure 2-10: The pointer to a pointer variable is assigned the memory address of the ptInitial pointer Figure 2-11: Two memory addresses are referenced when using a pointer to a pointer to display a value on the screen Chapter 3: What Is an Array? Figure 3-1: Elements of an array are stored sequentially in memory Figure 3-2: A two-dimensional array is a multidimensional array consisting of two arrays Figure 3-3: All three grades can be stored in a multidimensional array Figure 3-4: Elements of a multidimensional array are stored sequentially in memory Figure 3-5: Braces define sets of values to be assigned to array elements (the top example is C and C++ and the bottom example is Java) Figure 3-6: Display the contents of array elements by referencing the index of both sets of array elements Figure 3-7: Use the array name as a pointer to the first array element Figure 3-8: Memory allocation after the pointer is assigned the address of the first array element Figure 3-9: Using the content pointed to by an array of pointers Figure 3-10: An array of pointers to pointers reorganizes names without changing the order of the array that contains the names Figure 3-11: Using a pointer array and an array of pointers to pointers to display the contents of an array of strings Chapter 4: Stacks Using an Array Figure 4-1: A stack and an array are two different things: an array stores values in memory; a stack tracks which of the array elements is at the top of the stack Figure 4-2: The new value is assigned to the next array element and its index becomes the top of the stack Figure 4-3: All values move toward the top of the stack when the top item is popped off the stack Chapter 5: Queues Using an Array Figure 5-1: The queue is different from the array used to store data that appears in the queue Figure 5-2: The enqueue process places a new value at the back of the queue Figure 5-3: The dequeue process removes an item from the front of a queue Figure 5-4: The isFull() member function determines if there is room to place another item on the back of the queue Figure 5-5: The isEmpty() member function determines if the queue contains any values Figure 5-6: Here’s the queue and the array after the last call to the enqueue() member function is made Chapter 6: What Is a Linked List? Figure 6-1: Students are seated in a classroom in random order Figure 6-2: A node contains reference to the next node and the previous node in the linked list and contains data that is associated with the current node Figure 6-3: A doubly linked list contains next and previous members, and a single linked list contains only a next member Figure 6-4: The appendNode() member function changes what nodes are pointed to in the linked list Figure 6-5: The previous member of each node transverses the linked list Figure 6-6: The destroyList() member function removes nodes beginning with the last node on the linked list and works its way to the beginning of the linked list Chapter 7: Stacks Using Linked Lists Figure 7-1: A node contains references to the previous node and the next node in the linked list and contains data that is associated with the current node Figure 7-2: The pop() member function removes the node at the top of the stack, which is the node at the front of the linked list Figure 7-3: Before the pop() member function is called, there are three nodes on the stack Two nodes remain after pop() is called Chapter 8: Queues Using Linked Lists Figure 8-1: Each node points to the previous node and the next node Figure 8-2: A new node is added to the queue at the back of the linked list Figure 8-3: Node 1 is removed from the back of the queue by the dequeue() member function Figure 8-4: The queue after all three values are placed on the queue Figure 8-5: The queue after the dequeue() member function is called Figure 8-6: The queue after all values are placed on the queue Chapter 9: Stacks and Queues: Insert, Delete, Peek, Find Figure 9-1: A linked list containing five nodes with each node identified by an index value Figure 9-2: The linked list after NodeC is removed Figure 9-3: A new node called NodeN is placed in index position 2 within the linked list Figure 9-4: The top is the linked list before the node is removed, the middle is after removeNodeAt(3) is called, and the bottom is after deleteNode(2) is called Figure 9-5: The linked list after the insertNodeAt(1) is called Chapter 10: What Is a Tree? Figure 10-1: A binary tree is a tree where each stem has no more than two branches Figure 10-2: A binary tree is comprised of several nodes, each of which are related to other nodes on the tree Figure 10-3: The number of levels in a tree defines a tree’s depth, and the number of nodes defines the size of the tree Figure 10-4: The left child node is always less than the parent node, and the right child node is always greater than the parent node Figure 10-5: Each node has an index and a value; the index uniquely identifies the node and retrieves the value of a node Figure 10-6: Regardless of the order in which data is added to the tree, the left child node is less than the parent node and the right child node is greater than the parent node Figure 10-7: The left child node is removed from the tree; the tree still has a depth of two levels Chapter 11: What Is a Hashtable? Figure 11-1: The hashtable is an array whose elements point to userdefined structures that contain data Figure 11-2: A linked list connects user-defined structures whose keys hash to the same hash value Figure 11-3: The constructor declares an array of pointers where each element of the array points to an instance of the metadata structure Figure 11-4: Here’s what happens after the first entry is placed on the hashtable by calling the put() function Figure 11-5: The hashtable created after the put() function is called for the last time List of Tables Chapter 1: Memory, Abstract Data Types, and Addresses Table 1-1: Combinations of Two Bits and Their Decimal Value Equivalents Table 1-2: Simple Java Data Types ... the rest of the chapters on data structures In order to learn data structures, you must have some computer programming skills—computer programming is the language used to create data structures But don’t be... If you’ve been searching for that quick, easy-tounderstand guide to walk you through data structures, look no further Data Structures Demystified is all these things and more Whether you’re trying to program stacks and linked lists or figure out... Searching lists is one of the many ways data structures help you manipulate data that is stored in your computer’s memory However, before you can understand how to use data structures, you need to have a firm grip on how computer