Data StructuresWhat You Will LearnIntroductionSelf-Referential ClassesSlide 5Dynamic Memory AllocationSlide 7Linked ListsLists and Linked ListsLinked ListSlide 11Slide 12Declaration for a Linked ListDynamic Allocation of List NodesDynamic AllocationLinking Nodes TogetherCharacteristics of Singly Linked ListsConstructing a ListConstructing List (version 2)Constructing a List (Version 2)Slide 21Slide 22Slide 23Traversing a ListRecursive List TraversalSlide 26InsertionsLinked Lists - Removing NodesDeletionsSlide 30Slide 31Disadvantages of Dynamic Linked ListHead NodesDoubly Linked ListsCircular Linked ListsCircular Linked ListStacksSlide 38Stacks -- ApplicationsQueuesQueues -- ApplicationsTreesSlide 43Slide 441Data StructuresChapter 152What You Will LearnListsListsQueuesQueuesTreesTreesStacksStacks3IntroductionPreviously used fixed sized data structuresarraysstructsNow we will use dynamic data structuresthey will grow and shrink during executionExamplesstacksqueuesbinary trees4Self-Referential ClassesA self-referential class contains a pointer member that points to a class object of the same class typeclass Part_node { public: Part_node ( ); … private: char part_num[8], descrip[20]; int qty; float price; Part_node *next_part; } ;class Part_node { public: Part_node ( ); … private: char part_num[8], descrip[20]; int qty; float price; Part_node *next_part; } ;5Self-Referential ClassesThis pointer to an object of the type being declared enables class objects to be linked together in various waysThis is how we get linked lists, stacks, queues0PointervariableLinkPointerMemberNullPointer6Dynamic Memory AllocationIf the data structures are to be dynamic, then dynamic memory allocation is requiredoperators new and delete are essential part_node *newPtr = new part_node; part_node *newPtr = new part_node; Creates thenew pointerAllocates the space fora new part node07Dynamic Memory AllocationThe delete operator deallocates memory allocated with the newNote: newPtr is not itself deleted -- rather the space newPtr points to 0 delete newPtr; delete newPtr;8Linked ListsDefinition <=> A list of self-referential class objectscalled nodesconnected by pointer links (thus, a "linked" list)Subsequent nodes accessed via link-pointer member stored in each memberLink pointer in last node set to null (zero)marks the end of the listNodes created dynamically, as needed9Lists and Linked ListsCriteria for choosing linked listmust be linear, homogeneous datarules out sets & recordsordering does not depend on time of insertionrules out FIFO, LIFOsequential access is sufficientrules out need for arrayfrequent insert, delete and requirement for sorting10Linked ListCollection of structs (called nodes)One member is the data memberAt least one other member of the struct gives location of next member This makes it self referentialhead77-3/-3/4411Linked ListNodes do not necessarily occupy consecutive memory locationsTwo ways to implementDynamic data with pointers (this is what our text is advocating)Also possible to use built in arrays12Linked ListAbstractions that are implemented using built-in typesI m p l e m e n t a t i o n H i e r a r c h y f o r a l i s t A D TB u i l t - i n A r r a yB u i l t - i n D y n a m i cd a t a a n d p o i n t e r sB u i l t - i n A r r a yL i n k e d L i s tL i s t13Declaration for a Linked List// Declarationstruct NodeType;typedef Nodetype* NodePtr;struct NodeType{ SomeDataType data; NodePtr link; };NodePtr head;NodePtr visitPtr;Forward (incomplete)declarationForward (incomplete)declarationCompletedeclarationCompletedeclaration14Dynamic Allocation of List Nodes// Allocate a new dynamic objecthead = new NodeType;(*head).data = 345;Newly allocated object is a struct with 2 members345345headdatalink15Dynamic Allocation(*head).data (*head) is pointer dereferencing .data is struct selectionEquivalent (and easier to use) head ->dataThus we could have said head->data =345;16Linking Nodes TogetherHead->link refers to …Thus head->link = new NodeTypewill allocate a second NodeType struct, pointed to by the link element of the firstThen think what happens ...head->link->data = 12;head->link->link = NULL;345345headdatalink17Characteristics of Singly Linked ListsIn previous slide, head is a pointer only, not a node on the list*head is the struct pointed to by the headhead->link or (*head).link is the address of the second struct*(head->link) or *((*head).link) is the entire second structhead->link->data is the data member of the second struct18Constructing a ListAlgorithmhead = new NodeType;currentPtr = head;do { currentPtr->link = NULL; // do something with currentPtr->data if (! done) { currentPtr->link = new NodeType; currentPtr =currentPtr->link; } } while (! done);19Constructing List (version 2)ReadCities (/*out*/ CityPtr& cityList){CityPtr inNode;CityName tempName;cityList = Null;while (cin >> tempName) { inNode = new CityNode; strcpy (inNode->name, tempName); cin >> inNode->population; cin >> inNode->numVoters; inNode->next = cityList; cityList = inNode; }}ReadCities (/*out*/ CityPtr& cityList){CityPtr inNode;CityName tempName;cityList = Null;while (cin >> tempName) { inNode = new CityNode; strcpy (inNode->name, tempName); cin >> inNode->population; cin >> inNode->numVoters; inNode->next = cityList; cityList = inNode; }}20Constructing a List (Version 2)inNodeinNodecityListcityListLongview7550NULL21Constructing a List (Version 2)inNodeinNodecityListcityListLongview7550NULLTyler806022Constructing a List (Version 2)inNodeinNodecityListcityListLongview7550NULLTyler8060Dallas100050023Constructing a List (Version 2)inNodeinNodecityListcityListLongview7550NULLTyler8060Dallas1000500Hallsville21(Remember this is a reference parameter)24Traversing a ListGeneral algorithmvisitPtr = head;while (visitPtr != NULL) { // do something with the visitPtr -> data visitPtr = visitPtr -> link;}25Recursive List TraversalRecursive routinevoid visit_list ( /* in */ visit_ptr NodePtr) { if (visit_ptr != NULL) { visit_list (visit_ptr->link); cout << visit_ptr -> data; } }Note that data is printed in reverse order of original inputRecursive CallRecursive Call26Linked ListsManipulate pointers
View Full Document