Unsorted Lists CS3240, L. Grewe
Goals Describe the Abstract Data Type Unsorted List from three perspectives Use the Unsorted List operations to implement utility routines to do the following application-level tasks: Print the list of elements Create a list of elements from a file Implement the following Unsorted List operations using an array-based implementation Create and destroy a list Determine whether the list is full Insert an element Retrieve an element Delete an element
Goals Write and execute a test plan for an abstract data type Declare variables of pointer types Access the variables to which pointers point Implement the list operations outlined above using a linked implementation Compare the two implementations of the ADT Unsorted List in terms of Big-O approximations
Lists Linear relationship Each element except the first has a unique predecessor, and each element except the last has a unique successor Length The number of items in a list; the length can vary over time Unsorted list A list in which data items are placed in no particular order; the only relationships between data elements are the list predecessor and successor relationships
Name some possible keys Lists Sorted list A list that is sorted by the value in the key; there is a semantic relationship among the keys of the items in the list Key The attributes that are used to determine the logical order of the list Name some possible keys
Abstract Data Type (ADT) ADT Unsorted List Abstract Data Type (ADT) A data type whose properties (domain and operations) are specified independently of any particular implementation Can you think of what operations we should provide for our ADT Unsorted List?
ADT Unsorted List Transformers Observers Iterators MakeEmpty InsertItem DeleteItem Observers IsFull GetLength RetrieveItem Iterators ResetList GetNextItem change state observe state process all 7
ADT Unsorted List Common vocabulary location accesses a particular element Node(location) is all data of element Info(location) is the user's data at location Info(last) user's data at the last location Next(location) is the node following Node(location) Two implementations
Public declarations are the same for either // SPECIFICATION FILE ( unsortedType.h ) #include “ItemType.h” class UnsortedType // declares a class data type { public : // 8 public member functions UnsortedType(); void MakeEmpty( ); bool IsFull( ) const; int GetLength( ) const; // returns length of list void RetrieveItem( ItemType& item, bool& found ); void InsertItem( ItemType item ); void DeleteItem( ItemType item ); void ResetList( ); void GetNextItem( ItemType& item ); Public declarations are the same for either implementation; only private data changes What is ItemType? 9
ADT Unsorted List Generic data type A type for which the operations are defined but the types of the items being manipulated are not defined How can we make the items on the list generic? List items are of class ItemType, which has a ComparedTo function that returns (LESS, GREATER, EQUAL)
ADT Unsorted List Constructor A special member function of a class that is implicitly invoked when a class object is defined UnsortedType(); Why do you need a constructor if you have an operation MakeEmpty?
Array-Based Implementation Private data members for array-based implementation private int length; ItemType info[MAX_ITEMS]; int currentPos; }; Where does MAX_ITEMS come from?
Array-Based Implementation Notice the difference between the array and the list stored in the array
Array-Based Implementation What should the constructor do? UnsortedType::UnsortedType() { length = 0; } 14
Array-Based Implementation What is a full list? An empty list? bool UnsortedType::IsFull() { return (length == MAX_ITMES); } bool UnsortedType::IsEmpty() return (length == 0); 15
Array-Based Implementation length 3 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] . [MAX_ITEMS-1] insert("Hsing"); If the list is unsorted, where should the next element go ? 16
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . . . [MAX_ITEMS-1] That was easy! Can you code it ? 17
Array-Based Implementation void UnsortedType::InsertItem(ItemType item) // Post: item is in the list. { info[length] = item; length++; } How would you go about finding an item in the list? Cycle through the list looking for the item
Array-Based Implementation What are the two ending cases? The item is found The item is not in the list How do we compare items? We use function ComparedTo in class ItemType
Array-Based Implementation Initialize location to position of first item Set found to false Set moreToSearch to (have not examined Info(last)) while moreToSearch AND NOT found switch (item.ComparedTo(Info(location))) case LESS : case GREATER : Set location to Next(location) case EQUAL : Set found to true Set item to Info(location) Replace bold general statements with array-based code
Array-Based Implementation void UnsortedType::RetrieveItem(ItemType& item, bool& found) // Pre: Key member(s) of item is initialized. // Post: If found, item's key matches an element's key in the // list and a copy of that element has been stored in item; // otherwise, item is unchanged. { bool moreToSearch; int location = 0; found = false; moreToSearch = (location < length); while (moreToSearch && !found) switch (item.ComparedTo(info[location])) { case LESS : case GREATER : location++; break; case EQUAL : found = true; item = info[location]; }
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] moreToSearch: true found: false location: 0 Search for Anderson 22
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] moreToSearch: true found: false location: 1 23
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] moreToSearch: true found: false location: 2 24
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] moreToSearch: true found: false location: 3 25
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . . . [MAX_ITEMS-1] moreToSearch: false found: false location: 4 26
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . . . [MAX_ITEMS-1] What are moreToSearch, location, and found at the end of a search for Bradley ? 27
Array-Based Implementation How do you delete an item? First you find the item Yes, but how do you delete it? Move those below it up on slot Replace it with another item What other item? How about the item at info[length-1]?
Array-Based Implementation void UnsortedType::DeleteItem ( ItemType item ) // Pre: item’s key has been inititalized. // An element in the list has a key that matches item’s. // Post: No element in the list has a key that matches item’s. { int location = 0 ; while (item.ComparedTo (info[location]) != EQUAL) location++; // move last element into position where item was located info [location] = info [length - 1 ] ; length-- ; } Why don't we have to check for end of list?
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] location: 0 Delete Bradley 30
Array-Based Implementation length 4 info [ 0 ] Maxwell [ 1 ] Bradley [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] location: 1 Key Bradley has been matched 31
Array-Based Implementation length 3 info [ 0 ] Maxwell [ 1 ] Hsing [ 2 ] Asad [ 3 ] Hsing . [MAX_ITEMS-1] location: 1 Copy of last list element is in the position where the key Bradley was before; length has been decremented 32
Array-Based Implementation void PrintList(ofstream& dataFile, UnsortedType list) // Pre: list has been initialized. // dataFile is open for writing. // Post: Each component in list has been written. // dataFile is still open. { int length; ItemType item; list.ResetList(); length = list.GetLength(); for (int counter = 1; counter <= length; counter++) list.GetNextItem(item); item.Print(dataFile); } How do ResetList and GetNextItem work?
Array-Based Implementation void UnsortedType::ResetList ( ) // Pre: List has been inititalized. // Post: Current position is prior to first element. { currentPos = -1 ; } void UnsortedType::GetNextItem ( ItemType& item ) // Pre: List has been initialized. Current position is // defined. // Element at current position is not last in list. // Post: Current position is updated to next position. // item is a copy of element at current position. currentPos++ ; item = info [currentPos] ; 34
Class ItemType // SPECIFICATION FILE itemtype.h ) const int MAX_ITEM = 5; enum RelationType { LESS, EQUAL, GREATER }; class ItemType // declares class data type { public : // 3 public member functions RelationType ComparedTo( ItemType ) const; void Print( ) const; void Initialize( int number ); private : // 1 private data member int value; // could be any type } ;
Class ItemType How would this class change if the items // IMPLEMENTATION FILE ( itemtype.cpp ) // Implementation depends on the data type of value. #include “itemtype.h” #include <iostream> RelationType ComparedTo( ItemType otherItem ) const { if ( value < otherItem.value ) return LESS; else if ( value > otherItem.value ) return GREATER; else return EQUAL; } void Print( ) const using namespace std; cout << value << endl; void Initialize( int number ) value = number; How would this class change if the items on the list were strings rather than integers ?
UML Diagram
Pointer Types Pointer variable A variable whose value is the address of a location in memory int* intPointer
Pointer Types int alpha; int* intPointer; intPointer = α If alpha is at address 33, memory looks like this Say again??
Pointer Types int x; x = 12; int* ptr; ptr = &x; 2000 12 x 3000 ptr NOTE: Because ptr holds the address of x, we say that ptr “points to” x
Pointer Types Dereference operator (*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points Dynamic allocation (new operator) Allocation of memory space for a variable at runt time (as opposed to static allocation at compile time)
Pointer Types *ptr is the value in the place to which ptr points 2000 12 x 3000 ptr int x; x = 12; int* ptr; ptr = &x; std::cout << *ptr; *ptr is the value in the place to which ptr points
Pointer Types int x; x = 12; int* ptr; ptr = &x; *ptr = 5; 2000 12 5 x // changes the value // at adddress ptr to 5 2000 12 5 x 3000 ptr
Pointer Types char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the right side has value 4000 // now p and q both point to ch 4000 A Z ch 5000 6000 4000 4000 q p
Pointer Types intPointer = new int;
Pointer Types NULL Pointer A pointer that points to nothing; available in cstddef Memory Leak The loss of available memory space that occurs when memory is allocated dynamically but never deallocated Garbage Memory locations that can no longer be accessed
Linked Implementation
Linked Implementation Be sure you understand the differences among location, *location, and location->info
Linked Implementation Remember the design notation? Node(location) *location Info(location) location->info Next(location) location->next How do you set location to Next (location)? How do you set Info(location) to value?
Linked Implementation Private data for the Unsorted List ADT, linked-list implementation private: NodeType* listData; int length; NodeType* currentPos; }; List with two items
Linked Implementation How do you know that a linked list is empty? listData is NULL What should the constructor do? Set length to 0 Set listData to NULL What about currentPos? We let ResetList take care of initializing currentPos You write the constructor
Linked Implementation What about the observers IsFull and GetLength? GetLength just returns length Can a linked list ever be full? Yes, if you run out of memory Ask for a new node within a try/catch
Linked Implementation bool Unsortedtype::IsFull() const { NodeType* location; try location = new NodeType; delete location; return false; } catch (std::bad_alloc exception) return true; What about MakeEmpty?
Linked Implementation void Unsortedtype::MakeEmpty() { NodeType* tempPtr; while (listData != NULL) tempPtr = listData; listData = listData->next; delete tempPr; } length = 0; Why can we just set listData to NULL?
Linked Implementation Initialize location to position of first item Set found to false Set moreToSearch to (have not examined Info(last)) while moreToSearch AND NOT found switch (item.ComparedTo(Info(location))) case LESS : case GREATER : Set location to Next(location) case EQUAL : Set found to true Set item to Info(location) Replace bold general statements with linked code
Linked Implementation void UnsortedType::RetrieveItem( ItemType& item, bool& found ) // Pre: Key member of item is initialized. // Post: If found, item’s key matches an element’s key in the list // and a copy of that element has been stored in item; otherwise, // item is unchanged. { bool moreToSearch; NodeType* location; location = listData; found = false ; moreToSearch = ( location != NULL ) while ( moreToSearch && !found ) { if ( item == location->info ) // match here { found = true; item = location->info; } else // advance pointer { location = location->next; moreToSearch = ( location != NULL ); 56
Linked Implmentation
Linked Implementation How do we go about building a linked list? Create a list of one item Get a node using new location = new NodeType Put value into info portion of node location->info = item Put pointer to node in external pointer listData = location 58
Linked Implementation We forgot something: We must put NULL in the Next position of the first node 59
Linked Implementation How do we add a node to our list? Get a node using new location = new NodeType Put value into info portion location->info = Item Put node into list … Where? Where should the node go? Does it matter?
Linked Implementation Now we must put the two parts together--carefully!
Liked Implementation These steps must be done in this order! Why?
Linked Implementation void UnsortedType::InsertItem ( ItemType item ) // Pre: list is not full and item is not in list. // Post: item is in the list; length has been incremented. { NodeType* location; // obtain and fill a node location = new NodeType<ItemType>; location->info = item; location->next = listData; listData = location; length++; }
Linked Implementation How do you delete an item? Find the item Remove the item
Linked Implementation NodeType* = listData; NodeTyype* tempLocation; // Find the item if (item.ComparedTo(listData->info == EQUAL) { // item in first location tempLocation = location; listData = listData->next; } else { while (item.ComparedTo((location->next)->info) != EQUAL) location = location->next; tempLocation = location->next; location->next = (location ->next)->next; delete tempLocation; location--;
Linked Implementation ResetList and GetNextItem What was currentPos in the array- based implementation? What would be the equivalent in a linked implementation?
Linked Implementation void UnsortedType::ResetList() { currentPos = NULL; } void UnsortedType::GetNextItem(ItemType& item) if (currentPos == NULL) currentPos = listData; else currentPos = currentPos->next; item = currentPos->info; Postcondition on GetNextItem has changed: Explain
UML Diagram Note the differences between the UML Diagrams for the two implementations
What must this function do? Class Destructors Recall: listData is deallocated when it goes out of scope but what listData points to is not deallocated Class Destructor A function that is implicitly called when class object goes out of scope ~UnsortedType(); // Destructor What must this function do?
Big-O Comparison Which array-based operations are O(1)? Which linked operations are O(1)? Which array-based operations are O(N)? Which linked operations are O(N)? Can you say which implementation is better?
C++ Tips Declaration Associates an identifier with a data object or data type Definition A declaration that has been bound to storage Declaration of a class in C++ is also a definition
C++ Tips Rules for constructors A constructor cannot return a function value, and has no return value type. A class may have several constructors. The compiler chooses the appropriate constructor by the number and types of parameters used. Constructor parameters are placed in a parameter list in the declaration of the class object. The parameterless constructor is the default constructor. If a class has at least one constructor, and an array of class objects is declared, then one of the constructors must be the default constructor, which is invoked for each element in the array.
C++ Tips Variable's lifetime The time during a program's execution when a variable has storage assigned to it global variable: entire execution of the program local variable: execution of the block in which it is declared dynamically allocated variable: from allocation to deallocation local variable with static modifier: entire execution of the program static int count;