Unsorted Lists CS3240, L. Grewe.

Slides:



Advertisements
Similar presentations
Sorted Lists CS Data Structures Sections 4.1, 4.2 & 4.3.
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Computer Science and Software Engineering University of Wisconsin - Platteville 5. LinkedList Yan Shi CS/SE 2630 Lecture Notes.
Chapter 3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element except the.
C++ Plus Data Structures ADTs Unsorted List and Sorted List
Unsorted Lists CS 308 – Data Structures. What is a list? A list is a homogeneous collection of elements. Linear relationship between elements: (1) Each.
1 C++ Plus Data Structures Nell Dale Chapter 1 Software Engineering Principles.
CS Data Structures Chapter 8 Lists Mehmet H Gunes
Chapter 4 ADT Sorted List.
1 Chapter 4 Stack and Queue ADT. 2 Stacks of Coins and Bills.
Implementing an Unsorted List as a Linked Structure CS 308 – Data Structures.
1 Nell Dale Chapter 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Dynamic Structures & Arrays.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
Implementing a Sorted List as a Linked Structure CS 308 – Data Structures.
Data Structures Using C++ 2E
Chapter 4 ADT Sorted List.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 3 ADT Unsorted List. Lecture 7 List Definitions Linear relationship Each element except the first has a unique predecessor, and Each element.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List operations.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
1 C++ Plus Data Structures Nell Dale Chapter 4 ADTs Stack and Queue Modified from the slides by Sylvia Sorkin, Community College of Baltimore County -
Chapter 1 Object Oriented Programming. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
3 ADT Unsorted List. List Definitions Linear relationship Each element except the first has a unique predecessor, and each element except the last has.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 17: Linked Lists.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Chapter 16 Linked Structures Dale/Weems/Headington.
1 Chapter 13-1 Applied Arrays: Lists and Strings Dale/Weems.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
1 Data Structures and Algorithms Stacks and Queues.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 4 ADT Sorted List. Sorted Type Class Interface Diagram SortedType class IsFull GetLength ResetList DeleteItem PutItem MakeEmpty GetItem Private.
What is a List? A list is a homogeneous collection of elements, with a linear relationship between elements. Each list element (except the first) has a.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
CS 302 – Data Structures Sections 3.1, 3.2, 3.4 & 3.5
1 Nell Dale Lecture 3 ADTs Unsorted List and Sorted List Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta.
CSI 1340 Introduction to Computer Science II Chapter 3 ADTs Unsorted List and Sorted List.
1 Chapter 4 ADT Sorted List. 2 Sorted Type Class Interface Diagram SortedType class IsFull LengthIs ResetList DeleteItem InsertItem MakeEmpty RetrieveItem.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CSI 1340 Introduction to Computer Science II Chapter 6 Lists Plus.
Chapter 14 Dynamic Data and Linked Lists
CSCE 210 Data Structures and Algorithms
C++ Programming:. Program Design Including
Pointers and Linked Lists
Pointers and Linked Lists
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 13 Applied Arrays: Lists and Strings
C++ Plus Data Structures ADTs Unsorted List and Sorted List
TA: Nouf Al-Harbi Data Structures LAB 3 TA: Nouf Al-Harbi
CS Data Structures Chapter 8 Lists Mehmet H Gunes
C++ Plus Data Structures
Chapter 16-2 Linked Structures
C++ Plus Data Structures
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 16 Linked Structures
Data Structures & Algorithms
C++ Plus Data Structures
CSI 1340 Introduction to Computer Science II
Chapter 13 Applied Arrays: Lists and Strings
Yan Shi CS/SE 2630 Lecture Notes
Data Structures and Algorithms Memory allocation and Dynamic Array
TA: Nouf Al-Harbi Data Structures LAB 2 TA: Nouf Al-Harbi
Lists CMSC 202, Version 4/02.
Presentation transcript:

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;