C++ Programming: Program Design Including Data Structures, Second Edition Chapter 17: Linked Lists
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Objectives In this chapter you will: Learn about linked lists Become aware of the basic properties of linked lists Explore the insertion and deletion operations on linked lists Discover how to build and manipulate a linked list Learn how to construct a doubly linked list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Introduction Data can be organized and processed sequentially using an array, called a sequential list Problems with an array Array size is fixed Unsorted array: searching for an item is slow Sorted array: insertion and deletion is slow
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Linked Lists Linked list: collection of components (nodes) A list is a homogeneous collection of elements, with a linear relationship between elements. That is, each list element (except the first) has a unique predecessor, and each element (except the last) has a unique successor. Every node (except last) has address of next node Every node has two components Address of the first node of the list is stored in a separate location, called head or first
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, A Single Node.info.link ‘D ’ The user’s data Pointer to the next node in the stack
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Pointer-Based linked structure Implementation It must be a pointer to a record (passive structure) that contains both The user information A pointer to the next node of the list struct NodeType { char info; NodeType* link; }. info. link ‘A’ 6000
expanded by J. Goetz, Pointer Dereferencing and Member Selection. info. link ‘A’ 6000 first. info. link ‘A’ 6000 *first ptr. info. link (*first).info equivalent to first->info ‘A’ 6000
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Linked Lists (continued) A list of items, called nodes, in which the order of the nodes is determined by the address, called the link, stored in each node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Linked Lists (continued) The down arrow in the last node indicates that this link field is NULL The arrow in each node indicates that the address of the node to which it is pointing is stored in that node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Linked List (continued) Linked list above has four nodes Address of first node is stored in head Each node has two components: Info: stores the info Link: stores address of the next node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, current = head;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, current = current->link;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Traversing a Linked List The basic operations of a linked list are : Search to determine if an item is in the list Insert an item in the list Delete an item from the list Traversal: given a pointer to the first node of the list, step through the nodes of the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Traversing a Dynamic Linked List //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr or current 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL head
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr NULL 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //PRE: head points to a dynamic linked list ptr = head ; while (ptr != NULL) { cout info ; // Or, do something else with node *ptr ptr = ptr->link ; } ptr NULL 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL head Traversing a Dynamic Linked List
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insertion nodeType *head, *p, *q, *newNode; Consider the following linked list: A new node with info 50 is to be created and inserted after p
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insertion (continued) newNode = new nodeType; //create newNode newNode->info = 50; //store 50 in the new node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insertion (continued) newNode->link = p->link; p->link = newNode;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insertion (continued) newNode = new nodeType; //create newNode newNode->info = 50; //store 50 in the new node newNode->link = p->link; p->link = newNode;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Deletion Suppose the node with info 34 is to be deleted from the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Deletion (continued) After the statement: p->link = p->link->link; The resulting figure is: Node with info 34 is removed from the list Memory is still occupied; node is dangling so we need a pointer to this node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Deletion (continued) The following statements delete the node and deallocate the memory q = p->link; //(1) p->link = q->link; //(2) delete q; //(3) After the statement (1) q = p->link;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Deletion (continued) After the statement (2) p->link = q->link; the resulting figure is:
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Deletion (continued) After the statement (3) delete q; the resulting figure is:
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Building a Linked List If data is unsorted The list will be unsorted Can build a linked list forward or backward Forward: a new node is always inserted at the end of the linked list Backward: a new node is always inserted at the beginning of the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Building a Linked List Forward p insertLast() The new node is always inserted at the end of the list. enter data 2, 15, 8, 24, 34 You need three pointers to build the list: One to point to the first node in the list, which cannot be moved One to point to the last node in the list One to create the new node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Building a Linked List Backward p insertFirst() The new node is always inserted at the beginning of the list. enter data 2, 15, 8, 24, 34 You need two pointers to build the list: One to point to the first node in the list, which cannot be moved One to create the new node The algorithm is: 1.Initialize first to NULL 2.For each item in the list 1.Create the new node, newNode 2.Store the item in newNode 3.Insert newNode before first 4.Update the value of the pointer first
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Unordered Linked List as an ADT (Abstract Data Type) Using templates, this section gives you a generic definition of link lists. The basic operations on linked lists are: 1.Initialize the list 2.Determine whether the list is empty 3.Print the list 4.Find the length of the list 5.Destroy the list 6.Retrieve the info contained in the first node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Linked List as an ADT (continued) 7.Retrieve the info contained in the last node 8.Search the list for a given item 9.Insert an item in the list 10.Delete an item from the list 11.Make a copy of the linked list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, #ifndef H_LinkedListType // ADT #define H_LinkedListType #include #include // for assert statements using namespace std; //Definition of the node template struct nodeType { Type info; nodeType *link; }; template class linkedListType { public: const linkedListType & operator= (const linkedListType &); //Overload the assignment operator. void initializeList(); //Initialize the list to an empty state. //Postcondition: first = NULL, last = NULL, count = 0; bool isEmptyList() const; //Function to determine whether the list is empty. //Postcondition: Returns true if the list is empty, // otherwise it returns false. void print() const; //Function to output the data contained in each node. //Postcondition: none int length() const; //Function to return the number of nodes in the list. //Postcondition: The value of count is returned. void destroyList(); //Function to delete all the nodes from the list. //Postcondition: first = NULL, last = NULL, count = 0; Type front() const; //Function to return the first element of the list. //Precondition: The list must exist and must not be // empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the first // element of the list is returned. Type back()const; //Function to return the last element of the list. //Precondition: The list must exist and must not be // empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the last // element of the list is returned. bool search(const Type& searchItem) const; //Function to determine whether searchItem is in the list. //Postcondition: Returns true if searchItem is in the // list, otherwise the value false is // returned. void insertFirst(const Type& newItem); //Function to insert newItem at the beginning of the list. //Postcondition: first points to the new list, newItem is // inserted at the beginning of the list, // last points to the last node in the list, // and count is incremented by 1. void insertLast(const Type& newItem); //Function to insert newItem at the end of the list. //Postcondition: first points to the new list, newItem // is inserted at the end of the list, // last points to the last node in the list, // and count is incremented by 1. void deleteNode(const Type& deleteItem); //Function to delete deleteItem from the list. //Postcondition: If found, the node containing // deleteItem is deleted from the list. // first points to the first node, last // points to the last node of the updated // list, and count is decremented by 1. linkedListType(); //default constructor //Initializes the list to an empty state. //Postcondition: first = NULL, last = NULL, count = 0; linkedListType(const linkedListType & otherList); //copy constructor ~linkedListType(); //destructor //Deletes all the nodes from the list. //Postcondition: The list object is destroyed. protected: int count; //variable to store the number of elements in the list nodeType *first; //pointer to the first node of the list nodeType *last; //pointer to the last node of the list private: void copyList(const linkedListType & otherList); //Function to make a copy of otherList. //Postcondition: A copy of otherList is created and // assigned to this list. };
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template bool linkedListType ::isEmptyList() const { return(first == NULL); } template linkedListType ::linkedListType() //default constructor { first = NULL; last = NULL; count = 0; } template void linkedListType ::destroyList() { // traverse the list starting from the first node nodeType *temp; //pointer to deallocate the memory //occupied by the node while (first != NULL) //while there are nodes in the list { temp = first; //set temp to the current node first = first->link; //advance first to the next node delete temp; //deallocate the memory occupied by temp } last = NULL; //initialize last to NULL; first has already //been set to NULL by the while loop count = 0; } template void linkedListType ::initializeList() { //Initialize the list to an empty state. destroyList(); //if the list has any nodes, delete them } template void linkedListType ::print() const { //Function to output the data contained in each node. nodeType *current; //pointer to traverse the list current = first; //set current so that it points to the first node while (current != NULL) //while more data to print { cout info << " "; current = current->link; } }//end print template int linkedListType ::length() const { return count; } //end length template Type linkedListType ::front() const { assert(last != NULL); return first->info; //return the info of the first node }//end front template Type linkedListType ::back() const { assert(last != NULL); return last->info; //return the info of the first node }//end back template bool linkedListType ::search(const Type& searchItem) const { //Function to determine whether searchItem is in the list. // it is not a random access so: must sequentially search nodeType *current; //pointer to traverse the list bool found = false; current = first; //set current to point to the first node in the list while (current != NULL && !found) //search the list if (current->info == searchItem) //searchItem is found found = true; else current = current->link; //make current point to the next node return found; }//end search template void linkedListType ::insertFirst(const Type& newItem) { //Function to insert newItem at the beginning of the list. nodeType *newNode; //pointer to create the new node newNode = new nodeType ; //create the new node assert(newNode != NULL); //if unable to allocate memory, terminate the program newNode->info = newItem; //store the new item in the node newNode->link = first; //insert newNode before first first = newNode; //make first point to the actual first node count++; //increment count if (last == NULL) //if the list was empty, newNode is also the last node in the list last = newNode; }//end insertFirst
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template void linkedListType ::insertLast(const Type& newItem) { //Function to insert newItem at the end of the list. nodeType *newNode; //pointer to create the new node newNode = new nodeType ; //create the new node assert(newNode != NULL);//if unable to allocate memory, //terminate the program newNode->info = newItem; //store the new item in the node newNode->link = NULL; //set the link field of newNode //to NULL if (first == NULL) //if the list is empty, newNode is //both the first and last node { first = newNode; last = newNode; count++;//increment count } else //the list is not empty, insert newNode after last { last->link = newNode; //insert newNode after last last = newNode; //make last point to the actual last node count++; //increment count } }//end insertLast Delete Node: template void linkedListType ::deleteNode(const Type& deleteItem) { // Function to delete the given deleteItem from the list. nodeType *current; //pointer to traverse the list for checking the info and delete node nodeType *trailCurrent; //pointer just before current to follow the current node bool found; // trailCurrent is as it were = beforeCurrent if (first == NULL) // Case 1; the list is empty. cout << "Cannot delete from an empty list.“ << endl; else { if (first->info == deleteItem) // Case 2 – the first node { current = first; first = first->link; count--; if (first == NULL) //the list has only one node last = NULL; delete current; } else // Case 3 or 4; search the list for the node with the given info { found = false; trailCurrent = first; //set trailCurrent to point to the first node current = first->link; //set current to point to the second node while (current != NULL && !found) // sequentially search from the 2 nd node { if (current->info != deleteItem) { trailCurrent = current; // advance movement current = current-> link; } else found = true; }//end while if (found) //Case 3; if found, delete the node { trailCurrent->link = current->link; count--; if (last == current) // Case 3 b node to be deleted was the last node last = trailCurrent; //update the value of last delete current; //delete the node from the list } else //Case 4 cout << "The item to be deleted is not in " << "the list." << endl; }//end else }//end deleteNode Case 1: List is empty If the list is empty, output an error message Case 2: List is not empty The node to be deleted is the first node After deletion, the list becomes empty
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued) Consider the list of more than one node, as shown in the figure below; delete 28
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued)
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued) Case 3: Node to be deleted is not first node, but is somewhere in this list Case 3a: Node to be deleted is not last node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued)
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued) Case 3b: Node to be deleted is the last node
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template void linkedListType ::copyList (const linkedListType & otherList) { // make a copy of otherList. nodeType *newNode; //pointer to create a node nodeType *current; //pointer to traverse the list if (first != NULL) //if the list is nonempty, make it empty destroyList(); if (otherList.first == NULL) //otherList is empty { first = NULL; last = NULL; count = 0; } else { current = otherList.first; //current points to the list to be copied count = otherList.count; //copy the first node first = new nodeType ; // a. create the node assert(first != NULL); first->info = current->info; // b. copy the info and first->link = NULL; //set the link field of the node to NULL last = first; //make last point to the first node current = current->link; //make current point to the next node in otherList // copy the remaining list while (current != NULL) { newNode = new nodeType ; //a. create the node assert(newNode != NULL); newNode->info = current->info; //b. copy the info and newNode->link = NULL; //set the link of newNode to NULL last->link = newNode; //c. insert newNode after last last = newNode; //make last point to the actual node current = current->link; // make current point to the next node in otherList }//end while }//end else }//end copyList template linkedListType ::~linkedListType() //destructor { // Deletes all the nodes from the list. // needed b/c memory is allocated dynamically – pointer data members destroyList(); }//end destructor template linkedListType ::linkedListType (const linkedListType & otherList) { // needed b/c memory is allocated dynamically – pointer data members first = NULL; // b/c copyList(otherList) is checking at the beginning if the original object is empty – it is copyList(otherList); }//end copy constructor – executes when an object is declared and initialized //overload the assignment operator template const linkedListType & linkedListType ::operator= (const linkedListType & otherList) { if (this != &otherList) //avoid self-copy { copyList(otherList); }//end else return *this; } #endif
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, //This program tests various operation of a linked list #include #include "linkedList.h" using namespace std; int main() { linkedListType list1, list2; //Line 1 int num; //Line 2 cout<<"Line 3: Enter numbers ending with -999"<endl; //Line 3 cin>>num; //Line 4 while(num != -999) //Line 5 { list1.insertLast(num); //Line 6 cin>>num; //Line 7 } cout<<endl; //Line 8 cout<<"Line 9: List 1: "; //Line 9 list1.print(); //Line 10 cout<<endl; //Line 11 cout<<"Line 12: Length List 1: "<<list1.length()<<endl; //Line 12 list2 = list1; //test the assignment operator Line 13 cout<<"Line 16: List 2: "; //Line 14 list2.print(); //Line 15 cout<<endl; //Line 16 cout<<"Line 17: Length List 2: "<<list2.length()<<endl;//Line 17 cout<<"Line 18: Enter the number to be "<<"deleted: ";//Line 18 cin>>num; //Line 19 cout<<endl; //Line 20 list2.deleteNode(num); //Line 21 cout<<"Line 22: After deleting the node, " <<"List 2: "<<endl; //Line 22 list2.print(); //Line 23 cout<<endl; //Line 24 cout<<"Line 25: Length List 2: "<<list2.length()<<endl; //Line 25 return 0; }
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Ordered Linked Lists Operations performed on a (ordered) list: 1.Initialize the list 2.Determine whether the list is empty 3.Print the list 4.Print the list in reverse order (new) 5.Destroy the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Ordered Linked Lists (continued) 6.Search the list for a given item 7.Insert an item in the list 8.Delete an item from the list 9.Find the length of the list 10.Make a copy of the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Ordered Linked Lists −We don’t need to have operations related to unordered linked list as follows: −Insert in the first node −Insert the last node −b/c now elements are ordered according some criteria −The last pointer is not needed for ordered linked list functions, so it is set to NULL −Many operations are similar or the same on unordered linked list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template class orderedLinkedListType: public linkedListType { public: bool search(const Type& searchItem) const; //Function to determine whether searchItem is in the list. //Postcondition: Returns true if searchItem is in the list, // otherwise the value false is returned. void insertNode(const Type& newItem); //Function to insert newItem in the list. //Postcondition: first points to the new list, newItem // is inserted at the proper place in the // list, and count is incremented by 1. void deleteNode(const Type& deleteItem); //Function to delete deleteItem from the list. //Postcondition: If found, the node containing // deleteItem is deleted from the list; // first points to the first node of the // new list, and count is decremented by 1. // If deleteItem is not in the list, an // appropriate message is printed. void printListReverse() const; //Function to print the list in reverse order. //Because the original list is in ascending order, the //elements are printed in descending order. private: void reversePrint(nodeType *current) const; //This function is called by the public member //function to print the list in reverse order. };
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template bool orderedListType ::search(const Type& searchItem) const { //Function to determine whether searchItem is in the list. // it is not a random access so: must sequentially search nodeType *current; //pointer to traverse the list bool found = false; current = first; //start the search at the 1 st node while (current != NULL && !found) //search the list if (current->info >= searchItem) //searchItem is found found = true; // found the proper place else current = current->link; //make current point to the next node if (found) found = (current->info == searchItem); //test for equality return found; }//end search // a new part in comparison to linkedListType:: search() is in color
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template void orderedLinkedListType ::insertNode(const Type& newItem) { nodeType *current; //pointer to traverse the list nodeType *trailCurrent; //pointer just before current like in delete for unordered linked list nodeType *newNode; //pointer to create a node bool found; newNode = new nodeType ; //create the node assert(newNode != NULL); newNode->info = newItem; //store newItem in the node newNode->link = NULL; //set the link field of the node to NULL if (first == NULL) //Case 1 – initially empty { first = newNode; count++; } else { current = first; found = false; while (current != NULL && !found) //search the list if (current->info >= newItem) found = true; else { trailCurrent = current; current = current->link; } if (current == first) //Case 2 – newItem is the smallest { newNode->link = first; first = newNode; count++; } else //Case 3 – inserted somewhere in the list including the largest { trailCurrent->link = newNode; newNode->link = current; count++; } }//end else }//end insertNode Case 2: The list is not empty, and item = 10 to be inserted is smaller than smallest item in list Case 3: list is not empty, and item to be inserted is larger than first item in list Case 3a: item = 65 to be inserted is larger than largest item in list (goes at end) Case 3b: The item = 27 to be inserted goes somewhere in the middle of the list Warning: Treat all figures with last = NULL (base class set this) The last pointer is not necessary for ordered linked list functions
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insert a Node (continued) Case 3: list is not empty, and item to be inserted is larger than first item in list Case 3a: item to be inserted is larger than largest item in list (goes at end) Warning: Treat all figures with last = NULL (base class set this) −The last pointer is not necessary for ordered linked list functions
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Case 3b: The item to be inserted goes somewhere in the middle of the list Warning: Treat all figures with last = NULL (base class set this) −The last pointer is not necessary for ordered linked list functions
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template // the function is the same as the delete operation on general // linkedlistType but it can be improved void orderedLinkedListType ::deleteNode(const Type& deleteItem) { nodeType *current; //pointer to traverse the list nodeType *trailCurrent; //pointer just before current bool found; if (first == NULL) //Case 1 empty list cout << "Cannot delete from an empty list." << endl; else { current = first; found = false; while (current != NULL && !found) //search the list if (current->info >= deleteItem) found = true; else { trailCurrent = current; // advance movement current = current->link; } if (current == NULL) //Case 4 the list is not empty and the item is not in the list cout << "The item to be deleted is not in the " << "list." << endl; else if (current->info == deleteItem) //the item to be deleted is in the list { if (first == current) //Case 2 the first node to be deleted { first = first->link; delete current; } else //Case 3 the item to be deleted is somewhere in the list { trailCurrent->link = current->link; delete current; } count--; } else //Case 4 cout << "The item to be deleted is not in the " << "list." << endl; } }//end deleteNode template void linkedListType ::deleteNode(const Type& deleteItem) { // Function to delete the given deleteItem from the list. nodeType *current; //pointer to traverse the list for checking the info and delete node nodeType *trailCurrent; //pointer just before current to follow the current node bool found; // trailCurrent is as it were = beforeCurrent if (first == NULL) // Case 1; the list is empty. cout << "Cannot delete from an empty list.“ << endl; else { if (first->info == deleteItem) // Case 2 – the first node { current = first; first = first->link; count--; if (first == NULL) //the list has only one node last = NULL; delete current; } else // Case 3 or 4; search the list for the node with the given info { found = false; trailCurrent = first; //set trailCurrent to point to the first node current = first->link; //set current to point to the second node while (current != NULL && !found) // sequentially search from the 2 nd node { if (current->info != deleteItem) { trailCurrent = current; // advance movement current = current-> link; } else found = true; }//end while if (found) //Case 3; if found, delete the node { trailCurrent->link = current->link; count--; if (last == current) // Case 3 b node to be deleted was the last node last = trailCurrent; //update the value of last delete current; //delete the node from the list } else //Case 4 cout << "The item to be deleted is not in " << "the list." << endl; }//end else }//end deleteNode
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Print List in Reverse Order Assume current is a pointer to a linked list that is in ascending order if(current != NULL) { reversePrint(current->link); //print the tail of the list cout info<<endl; //print the node } Base case is hidden (else part) Print only if pointer is not NULL Inside if statement recursive call is on tail node When control comes back to calling function, the remaining statements execute
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template void orderedLinkedListType ::reversePrint (nodeType *current) const // (1) { if (current != NULL) // (2) { reversePrint(current->link); // (3) print the tail of list cout info << " "; // (4) print the node } } // (5) // Base case is hidden template void orderedLinkedListType ::printListReverse() const { reversePrint(first); cout << endl; } // first -> 5 -> 10 -> 15 -> 20 -> NULL
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Doubly Linked Lists Doubly linked list: every node has next and back pointers Can be traversed in either direction struct nodeType { Type info; nodeType *next; nodeType *back; };
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, template class doublyLinkedList { public: const doublyLinkedList & operator= (const doublyLinkedList &); //Overload the assignment operator. void initializeList(); //Function to initialize the list to an empty state. //Postcondition: first = NULL; last = NULL; count = 0; bool isEmptyList() const; //Function to determine whether the list is empty. //Postcondition: Returns true if the list is empty, // otherwise returns false. void destroy(); //Function to delete all the nodes from the list. //Postcondition: first = NULL; last = NULL; count = 0; void printList() const; //Function to output the info contained in each node. void reversePrint() const; //Function to output the info contained in each node //in reverse order. int length()const; //Function to return the number of nodes in the list. //Postcondition: The value of count is returned. Type front() const; //Function to return the first element of the list. //Precondition: The list must exist and must not be empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the first // element of the list is returned. Type back()const; //Function to return the last element of the list. //Precondition: The list must exist and must not be empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the last // element of the list is returned. bool search(const Type& searchItem) const; //Function to determine whether searchItem is in the list. //Postcondition: Returns true if searchItem is found in // the list, otherwise returns false. void insertNode(const Type& insertItem); //Function to insert newItem in the list. //Precondition: If the list is nonempty, it must be in // order. //Postcondition: insertItem is inserted at the proper place // in the list, first points to the first // node, last points to the last node of the // new list, and count is incremented by 1. void deleteNode(const Type& deleteItem); //Function to delete deleteItem from the list. //Postcondition: If found, the node containing deleteItem // is deleted from the list; first points // to the first node of the new list, last // points to the last node of the new list, // and count is decremented by 1; otherwise, // an appropriate message is printed. doublyLinkedList(); //default constructor //Initializes the list to an empty state. //Postcondition: first = NULL; last = NULL; count = 0; doublyLinkedList(const doublyLinkedList & otherList); //copy constructor ~doublyLinkedList(); //destructor //Postcondition: The list object is destroyed. protected: int count; nodeType *first; //pointer to the first node nodeType *last; //pointer to the last node private: void copyList(const doublyLinkedList & otherList); //Function to make a copy of otherList. //Postcondition: A copy of otherList is created and // assigned to this list. };
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Because we can traverse in either direction, we use only one pointer to traverse the list we can set the value of trailCurrent by using both the current pointer and the back pointer of the node pointed by current Doubly Linked Lists
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Doubly Linked Lists (continued) Operations: 1.Initialize the list 2.Destroy the list 3.Determine whether the list is empty 4.Determine whether the list is full 5.Search the list for a given item 6.Retrieve the first element of the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Doubly Linked Lists (continued) Operations (continued): 7.Retrieve the last element of the list 8.Insert an item in the list 9.Delete an item from the list 10.Find the length of the list 11.Print the list 12.Make a copy of the doubly linked list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Insert a Node p.981 To insert a node, adjust two pointers There are four cases: 1.Insertion in an empty list 2.Insertion at the beginning of a nonempty list 3.Insertion at the end of a nonempty list 4.Insertion somewhere in a nonempty list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node The delete operation has several cases: 1.The list is empty 2.Item to delete is in first node: must change the value of the pointer first 3.The item to be deleted is somewhere in the list 4.The item to be deleted is not in the list
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Delete a Node (continued) Case 3: Consider the list shown in the figure below
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, (1) (2) (3) (4) delete current
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Programming Example A new video store in your neighborhood is about to open However, it does not have a program to keep track of its videos and customers The store managers want someone to write a program for their system so that the video store can operate
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Programming Example (continued) The program should be able to perform the following operations: Rent a video; that is, check out a video Return, or check in, a video Create a list of videos owned by the store Show the details of a particular video Print a list of all videos in the store Check whether a particular video is in the store Maintain a customer database Print list of all videos rented by each customer
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Programming Example (continued) There are two major components of the video store: A video A customer You need to maintain two lists: 1.A list of all videos in the store 2.A list of all customers of the store
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Part 1: Video Component The common things associated with a video are: Name of the movie Names of the stars Name of the producer Name of the director Name of the production company Number of copies in store
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Video List This program requires us to Maintain a list of all videos in the store Add a new video to our list Use a linked list to create a list of videos
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Part 2: Customer Component Primary characteristics of a customer: First name Last name Account number List of rented videos
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz,
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Basic Operations Basic operations on personType: Print the name Set the name Show the first name Show the last name
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Basic Operations (continued) Basic operations on an object of the type customerType are: Print name, account #, and number of rentals Set name, account #, and number of rentals Rent a video, add video to the list Return a video, delete video from the list Show account #
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Main Program The data in the input file is in the form: video title movie star1 movie star2 movie producer movie director movie production co. number of copies.
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Algorithm of the Main Function Open the input file, exit if not found createVideoList: create the list of videos displayMenu: show the menu While not done, perform various tasks
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, CreateVideoList 1.Read data and store in a video object 2.Insert video in list 3.Repeat steps 1 and 2 for each video in file
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, displayMenu Select one of the following 1.Check whether a particular video is in the store 2.Check out a video 3.Check in a video 4.Check whether a particular video is in the store 5.Print the titles of all videos 6.Print a list of all videos 9.Exit
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Summary A linked list is a list of items (nodes) Order of the nodes is determined by the address, called a link, stored in each node The pointer to a linked list is called head or first A linked list is a dynamic data structure The list length is the number of nodes
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Summary Insertion and deletion does not require data movement; only the pointers are adjusted A (single) linked list is traversed in only one direction Search of a linked list is sequential The head pointer is fixed on first node Traverse: use a pointer other than head
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, Summary Header and trailer nodes simplifies insertion and deletion operations A linked list with header and trailer nodes is empty if the only nodes in the list are the header and the trailer Doubly linked list Every node has two links: next and previous Can be traversed in either direction Item insertion and deletion require the adjustment of two pointers in a node