Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Programming: Program Design Including Data Structures, Second Edition Chapter 17: Linked Lists.

Similar presentations


Presentation on theme: "C++ Programming: Program Design Including Data Structures, Second Edition Chapter 17: Linked Lists."— Presentation transcript:

1 C++ Programming: Program Design Including Data Structures, Second Edition Chapter 17: Linked Lists

2 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 2 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

3 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 3 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

4 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 4 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

5 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 5 A Single Node.info.link ‘D ’ The user’s data Pointer to the next node in the stack

6 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 6 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

7 expanded by J. Goetz, 2004 7 7 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

8 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 8 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

9 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 9 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

10 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 10 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

11 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 11

12 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 12 current = head;

13 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 13 current = current->link;

14 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 14

15 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 15 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

16 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 16 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 3000 5000 2000 head

17 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 17 //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 3000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

18 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 18 //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 3000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

19 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 19 //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 3000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

20 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 20 //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 5000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

21 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 21 //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 5000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

22 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 22 //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 5000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

23 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 23 //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 2000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

24 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 24 //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 2000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

25 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 25 //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 2000 3000 “Ted” 5000 “Irv” 2000 “Lee” NULL 3000 5000 2000 head Traversing a Dynamic Linked List

26 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 26 //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 3000 5000 2000 head Traversing a Dynamic Linked List

27 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 27 //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 3000 5000 2000 head Traversing a Dynamic Linked List

28 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 28 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

29 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 29 Insertion (continued) newNode = new nodeType; //create newNode newNode->info = 50; //store 50 in the new node

30 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 30 Insertion (continued) newNode->link = p->link; p->link = newNode;

31 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 31 Insertion (continued) newNode = new nodeType; //create newNode newNode->info = 50; //store 50 in the new node newNode->link = p->link; p->link = newNode;

32 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 32 Deletion Suppose the node with info 34 is to be deleted from the list

33 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 33 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

34 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 34 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;

35 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 35 Deletion (continued) After the statement (2) p->link = q->link; the resulting figure is:

36 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 36 Deletion (continued) After the statement (3) delete q; the resulting figure is:

37 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 37 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

38 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 38 Building a Linked List Forward p.940 - 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

39 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 39 Building a Linked List Backward p.941 - 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

40 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 40 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

41 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 41 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

42 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 42

43 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 43 #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. };

44 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 44 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

45 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 45 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

46 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 46 Delete a Node (continued) Consider the list of more than one node, as shown in the figure below; delete 28

47 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 47 Delete a Node (continued)

48 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 48 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

49 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 49 Delete a Node (continued)

50 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 50 Delete a Node (continued) Case 3b: Node to be deleted is the last node

51 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 51 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

52 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 52 //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; }

53 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 53 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

54 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 54 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

55 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 55 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

56 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 56 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. };

57 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 57 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

58 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 58 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

59 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 59 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

60 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 60 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

61 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 61 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

62 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 62 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

63 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 63 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

64 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 64

65 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 65 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; };

66 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 66 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. };

67 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 67 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

68 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 68 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

69 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 69 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

70 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 70 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

71 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 71 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

72 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 72 Delete a Node (continued) Case 3: Consider the list shown in the figure below

73 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 73 (1) (2) (3) (4) delete current

74 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 74 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

75 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 75 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

76 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 76 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

77 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 77 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

78 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 78

79 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 79

80 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 80 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

81 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 81

82 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 82

83 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 83 Part 2: Customer Component Primary characteristics of a customer: First name Last name Account number List of rented videos

84 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 84

85 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 85 Basic Operations Basic operations on personType: Print the name Set the name Show the first name Show the last name

86 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 86 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 #

87 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 87 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.

88 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 88 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

89 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 89 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

90 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 90 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

91 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 91 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

92 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 92 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

93 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004 93 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


Download ppt "C++ Programming: Program Design Including Data Structures, Second Edition Chapter 17: Linked Lists."

Similar presentations


Ads by Google