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, 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
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
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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
77
Pointer Dereferencing and Member Selection
. info . link
‘A’ 6000 first
first
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, 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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
11
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
12
• current = head;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
13
• current = current->link;
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
14
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
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 << ptr->info ;
// Or, do something else with node *ptr
ptr = ptr->link ;
}
ptrorcurrent
3000 “Ted” 5000 “Irv” 2000 “Lee” NULL
3000 5000 2000
head
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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 << ptr->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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
30
Insertion (continued)
newNode->link = p->link;
p->link = newNode;
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;
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
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
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;
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:
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:
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
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
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 NULL2. For each item in the list
1. Create the new node, newNode2. Store the item in newNode3. Insert newNode before first4. Update the value of the pointer first
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
42
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
43
#ifndef H_LinkedListType // ADT#define H_LinkedListType
#include <iostream>#include <cassert> // for assert statementsusing namespace std;
//Definition of the nodetemplate <class Type>struct nodeType{
Type info;nodeType<Type> *link;
};template<class Type>class linkedListType{public: const linkedListType<Type>& operator= (const linkedListType<Type>&); //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<Type>& 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<Type> *first; //pointer to the first node of the list nodeType<Type> *last; //pointer to the last node of the list
private: void copyList(const linkedListType<Type>& 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, 2004
44
template<class Type>bool linkedListType<Type>::isEmptyList() const{
return(first == NULL);}template<class Type>linkedListType<Type>::linkedListType() //default constructor{
first = NULL;last = NULL;
count = 0;}template<class Type>void linkedListType<Type>::destroyList(){ // traverse the list starting from the first node nodeType<Type> *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<class Type>void linkedListType<Type>::initializeList(){ //Initialize the list to an empty state.
destroyList(); //if the list has any nodes, delete them}template<class Type>void linkedListType<Type>::print() const{ //Function to output the data contained in each node.
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current so that it points to the first nodewhile (current != NULL) //while more data to print{ cout << current->info << " "; current = current->link;}
}//end printtemplate<class Type>int linkedListType<Type>::length() const{ return count;} //end length
template<class Type>Type linkedListType<Type>::front() const{ assert(last != NULL); return first->info; //return the info of the first node}//end front
template<class Type>Type linkedListType<Type>::back() const{ assert(last != NULL); return last->info; //return the info of the first node}//end back
template<class Type>bool linkedListType<Type>::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<Type> *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<class Type>void linkedListType<Type>::insertFirst(const Type& newItem){ //Function to insert newItem at the beginning of the list.
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //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, 2004
45
template<class Type>void linkedListType<Type>::insertLast(const Type& newItem){ //Function to insert newItem at the end of the list. nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //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 lastlast = newNode; //make last point to the actual last node
count++; //increment count }}//end insertLast
Delete Node:
template<class Type>void linkedListType<Type>::deleteNode(const Type& deleteItem){ // Function to delete the given deleteItem from the list. nodeType<Type> *current; //pointer to traverse the list for checking the info and delete node nodeType<Type> *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 2nd 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 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, 2004
46
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, 2004
47
Delete a Node (continued)
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
49
Delete a Node (continued)
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
51
template<class Type>void linkedListType<Type>::copyList (const linkedListType<Type>& otherList) { // make a copy of otherList.
nodeType<Type> *newNode; //pointer to create a node nodeType<Type> *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<Type>; // 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<Type>; //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<class Type>linkedListType<Type>::~linkedListType() //destructor{ // Deletes all the nodes from the list. // needed b/c memory is allocated dynamically – pointer data members destroyList();}//end destructor
template<class Type>linkedListType<Type>::linkedListType (const linkedListType<Type>& 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 operatortemplate<class Type>const linkedListType<Type>& linkedListType<Type>::operator= (const linkedListType<Type>& 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, 2004
52
//This program tests various operation of a linked list #include <iostream>#include "linkedList.h"using namespace std;
int main(){
linkedListType<int> list1, list2; //Line 1int num; //Line 2
cout<<"Line 3: Enter numbers ending with -999"<endl; //Line 3cin>>num; //Line 4
while(num != -999) //Line 5{
list1.insertLast(num); //Line 6cin>>num; //Line 7
}
cout<<endl; //Line 8cout<<"Line 9: List 1: "; //Line 9list1.print(); //Line 10cout<<endl; //Line 11cout<<"Line 12: Length List 1: "<<list1.length() <<endl; //Line 12
list2 = list1; //test the assignment operator Line 13
cout<<"Line 16: List 2: "; //Line 14list2.print(); //Line 15cout<<endl; //Line 16cout<<"Line 17: Length List 2: "<<list2.length() <<endl;//Line 17
cout<<"Line 18: Enter the number to be "<<"deleted: ";//Line 18cin>>num; //Line 19cout<<endl; //Line 20
list2.deleteNode(num); //Line 21
cout<<"Line 22: After deleting the node, " <<"List 2: "<<endl; //Line 22list2.print(); //Line 23cout<<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, 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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
56
template<class Type>class orderedLinkedListType: public linkedListType<Type>{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<Type> *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, 2004
57
template<class Type>bool orderedListType<Type>::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<Type> *current; //pointer to traverse the list bool found = false; current = first; //start the search at the 1st 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, 2004
58
template<class Type>void orderedLinkedListType<Type>::insertNode(const Type& newItem){ nodeType<Type> *current; //pointer to traverse the list nodeType<Type> *trailCurrent; //pointer just before current like in delete for unordered linked
list nodeType<Type> *newNode; //pointer to create a node
bool found;
newNode = new nodeType<Type>; //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, 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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
61
template<class Type> // the function is the same as the delete operation on general // linkedlistType but it can be improvedvoid orderedLinkedListType<Type>::deleteNode(const Type& deleteItem){ nodeType<Type> *current; //pointer to traverse the list nodeType<Type> *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<class Type>void linkedListType<Type>::deleteNode(const Type& deleteItem){ // Function to delete the given deleteItem from the list. nodeType<Type> *current; //pointer to traverse the list for checking the info and delete node nodeType<Type> *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 2nd 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 else}//end deleteNode
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 orderif(current != NULL){
reversePrint(current->link); //print the tail of the list cout<<current->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, 2004
63
template<class Type>void orderedLinkedListType<Type>::reversePrint
(nodeType<Type> *current) const // (1){ if (current != NULL) // (2) { reversePrint(current->link); // (3) print the tail of list cout << current->info << " "; // (4) print the node }} // (5)
// Base case is hidden
template<class Type>void orderedLinkedListType<Type>::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, 2004
64
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<Type> *next; nodeType<Type> *back; };
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
66
template<class Type>class doublyLinkedList{public: const doublyLinkedList<Type>& operator= (const doublyLinkedList<Type> &); //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<Type>& otherList); //copy constructor
~doublyLinkedList(); //destructor //Postcondition: The list object is destroyed.
protected: int count; nodeType<Type> *first; //pointer to the first node nodeType<Type> *last; //pointer to the last node
private: void copyList(const doublyLinkedList<Type>& 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, 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
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
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
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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
73
(1)
(2)
(3)
(4) delete current
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
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
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
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
78
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
79
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
81
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
82
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
C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004
84
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
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 #
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 titlemovie star1movie star2movie producermovie directormovie production co.number of copies...
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
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
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
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
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
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