0% found this document useful (0 votes)
15 views

Lesson 2p

This document discusses unsorted lists and their implementation using arrays. It covers: 1. The definition of an unsorted list as a collection of elements in no particular order, with operations like insertion, deletion, and retrieval. 2. How unsorted lists can be implemented using arrays, with constructors to initialize empty lists, transformers to modify lists, and observers to access list properties. 3. Details of implementing list operations like insertion, deletion, and retrieval using array indexing and movement or swapping of elements. Iterators are also discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lesson 2p

This document discusses unsorted lists and their implementation using arrays. It covers: 1. The definition of an unsorted list as a collection of elements in no particular order, with operations like insertion, deletion, and retrieval. 2. How unsorted lists can be implemented using arrays, with constructors to initialize empty lists, transformers to modify lists, and observers to access list properties. 3. Details of implementing list operations like insertion, deletion, and retrieval using array indexing and movement or swapping of elements. Iterators are also discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

6/10/18

Lists
l A list is a homogeneous collection of elements
Chapter 3 with a linear relationship between elements
l Linear Relationship: Each element except the
ADT Unsorted List first has a unique predecessor, and each
element except the last has a unique successor
l Length: The number of items in the list, which
can vary over time

List Definitions Unsorted List: Operations


l Unsorted List: A list in which data items are l Constructor: May make empty list or take some
placed in no particular order initial elements
l Sorted List: A list that is sorted by the keys of l Transformers: PutItem, DeleteItem, MakeEmpty
the list items; there is a semantic relationship l Observers: IsFull, GetLength
among the keys of the items in the list l Iterators: ResetList, GetNextItem
l Key: The attributes used to determine the
logical order of the list

1
6/10/18

What is a generic data type? Unsorted List: Application Level


l A type for which the operations are defined but l Unsorted lists seem to provide a few, limited
the types of the items being manipulated are operations
not defined l But it provides all the tools we need to write
l Our Unsorted List ADT simulates this by using a more specialized functions
user-defined class called ItemType that defines l Printing list items, reading items from a file, and
the member functions we need so on can all be written using this limited set of
operations

Unsorted List: Implementation Array vs. Linked List


l Different ways of storing items in memory affect
the performance of list operations
l Array-based: Elements are stored sequentially
in a contiguous chunk of memory
l Linked list-based: Elements are stored in
separate nodes, connected by pointers
l Using an array-based implementation for now

Figure 3.1 Comparison of Array and Linked Structure

2
6/10/18

Implementation: Constructors Class Constructor Rules


l Class Constructor: A special member function 1) A constructor cannot return a function value and has
that is implicitly invoked when a class object is no return value type
created 2) A class may have several constructors; the compiler
chooses the appropriate constructor by the number
- Used to initialize objects and allocate and types of parameters used
resources 3) Constructor parameters are placed in a parameter list
l For UnsortedType, the constructor sets the in the declaration of the class object: SomeClass
length to 0 anObject(param1, param2);
l No resources need to be allocated because the 4) The parameterless constructor is the default
size of the array is static constructor
5) A class must have a default (parameterless)
constructor in order to create arrays of that class

Implementation: Observers Implementation: Transformers


l IsFull and GetLength are straightforward l PutItem: Insert item at the end of the list,
l GetItem requires a linear search through the list increment length
- Use ItemType.CompareTo to check equality l DeleteItem: Linear search to find item, but how
- Use bool &found reference parameter to indicate to remove it?
success to the user - If the item is at the end of the list, just reduce the
- Return a copy of the found item length of the list by one
- But what about if it’s at the beginning?

3
6/10/18

Implementation: DeleteItem DeleteItem: Move or Swap?


Two strategies for removing an item in the middle
of an array-based list:
l Move Up: Move all items after the removed

item up one position; this is inefficient for long


lists
l Swap: The list is unordered, so copy the item at

the end of the list into the deleted item’s


position

Figure 3.4 Deleting an item in an unsorted list (a) Original list (b) Deleting Judy
(c) Deleting Bobby (move up) (d) Deleting Bobby (swap)

Implementation: Iterators Unsorted List: Test Plan


l The field currentPos indicates the current l Preconditions and postconditions determine the
position of iteration in the list black-box tests
l GetNextItem increments currentPos and l Code of functions determines clear-box tests
returns the item at that position l We make sure the tests touch upon edge
l ResetList must set currentPos to the first cases, such as the first and last items in the list,
item’s predecessor or a list with only one item
- For arrays, that’s -1

4
6/10/18

Pointer Types: Logical Level Pointer Operators


l A pointer variable contains the memory l The prefix ampersand (&) or “address of”
address of another variable operator returns the address of a variable:
l They are used for indirect addressing of data - int alpha = 10;
and for dynamic allocation of memory - intPointer = α
l Pointers are declared using an asterisk: - intPointer now contains alpha’s memory address
int* intPointer;
l The asterisk dereference operator (*) denotes
the variable to which a pointer points:
- *intPointer = 25; // alpha is now 25

Dynamic Allocation Dynamic Allocation (cont.)


l Dynamic Allocation: Allocation of memory l Dynamic allocation uses the keyword new:
space for a variable at run time, as opposed to - int* ptr = new int;
static allocation at compile time l new returns a pointer to the newly allocated int
l Dynamic allocation creates variables on the on the heap, and the value can only be
heap (or free store), a section of memory accessed via this pointer
reserved for dynamic allocation l Pointers can point to nothing using NULL
l If no memory is available on the heap, new
returns NULL

5
6/10/18

Memory Leak Memory Leak Example


l A memory leak is the loss of available memory float* money = new float;
space that occurs when some dynamically *money = 33.46;
allocated memory is never deallocated float* myMoney = new float;
l Dynamically allocated memory that can’t be
accessed is called garbage

Memory Leak Example (cont.) Memory Leak Example (cont.)


This copies the value pointed to by money into the This makes myMoney point to the same address
memory pointed to by myMoney: that money points to:
*myMoney = *money; myMoney = money;

6
6/10/18

Memory Leak Example (cont.) The Delete Operator


The memory cell originally used by myMoney is l The delete operator deallocates the memory
now inaccessible. Since there’s no way to collect pointed to by the argument
the garbage, it is a small memory leak. l Using delete myMoney would safely clean up
the memory allocated to myMoney
l C++ requires manual memory management

Pointers: Application Level Pointers: Implementation Level


l The name of an array variable when used l Pointers and dynamic memory are thankfully
without brackets is a pointer constant handled entirely by the operating system,
l Pointers can be used with constant types, compiler, and run-time system
allowing objects to link to each other l Except you must remember to delete
l If myPtr is a pointer to an object, the fields of dynamically allocated memory when you are
the object are accessed using the arrow finished with it!
operator: myPtr->field

7
6/10/18

UnsortedType as a Linked List Nodes


l Linked List: A collection of nodes that are
linked together in a chain using pointers
l Node: The basic component of a linked list;
stores data and a pointer to the next node
l Nodes are created when needed using
dynamically allocated memory
l The last node in the list has a NULL pointer

Figure 3.11 Node Terminology

PutItem Building the Chain


l When the list is empty, PutItem creates a node
and sets the external pointer listData to it

Figure 3.12 The second PutItem operation (a) new(location) (b) info(location)
<- newElement (c) Make next (location) point to List's tope node (d) Make List
point to the new node
Figure 3.9 Putting in the First Element

8
6/10/18

Length and Linked Lists Iterators


l For array-based lists, the length field must be l The array-based implementation used
present in order to define the extent of the list currentPos, an array index
within the array l Linked lists use a pointer to a node instead
l Linked lists don’t have this restriction l GetNextItem advances it: currentPos->next
l Instead of a field, GetLength could walk the list l ResetList sets it to NULL
and count the number of nodes - GetNextItem checks if it’s NULL and sets it to the
first item of the list

PutItem PutItem (cont.)


1) Create a new node void UnsortedType::PutItem (ItemType item)
// Pre: list is not full and item is not in list.
2) Set the node’s info to the input data // Post: item is in the list; length has been incremented.
{
3) Set the node’s next pointer to the listData, the NodeType<ItemType>* location;
first item in the list // create a new node and fill it
location = new NodeType<ItemType>;
4) Set listData to point to the new node location->info = item;
location->next = listData;
// the new node becomes head of the list
Order matters! Doing step 4 before step 3 would listData = location;
length++;
lead to a memory leak of the rest of the list. }

9
6/10/18

PutItem: Empty List Constructor


l Largely unchanged
l Set length to 0
l Set the external pointer to NULL

Figure 3.16 Putting an Item into an Empty List

IsFull IsFull (cont.)


bool UnsortedType::IsFull() const
l Linked lists don’t have an explicit size limit // Returns true if there is no room for another ItemType
l New nodes can be allocated until there is no // on the free store; false otherwise.
{
more memory to use NodeType* location;
try
l When this occurs, new will throw a bad_alloc {
location = new NodeType;
exception delete location;
l IsFull uses a try-catch block to allocate a node }
return false;

and returns true if a bad_alloc is thrown catch(std::bad_alloc exception)


{
return true;
}
}

10
6/10/18

MakeEmpty GetItem
l MakeEmpty must deallocate each node l The algorithm is unchanged: Linear search
individually in order to empty the list through the list to find the desired item
l This is accomplished using a while loop l In fact, the implementation is largely
l Iteration starts at listData, the head of the list, unchanged; it just needs to use pointers instead
and continues using listData->next of array indices
l Iteration stops when listData is NULL

GetItem (cont.) DeleteItem


l Deleting an item requires updating the pointer
of its predecessor
l Algorithm is the same, but search looks at the
item of location->next in order to have access to
the predecessor (location)

Figure 3.17 Retrieving an item in an unsorted linked list (a) Get Kit (b) Get Lila

11
6/10/18

DeleteItem (cont.) Lifetime of a Variable


l Lifetime: The time during execution that a
variable has memory assigned to it
l Global variable: The entire execution of a
program
l Local Variable: The execution of the block it is
in
l Dynamically allocated variable: From when it is
allocated to when it is deallocated
l The static keyword allows local variables to live
Figure 3.18 Deleting an interior node and deleting the first node (a) Delete Lila outside the time of their blocks
(b) Delete Kate

Class Destructors Comparing Implementations


l An object is deallocated when it leaves scope, l The array-based list allocates enough memory
but any data it points to is not – memory leak! for the max list size, no matter how many items
l A class destructor is a method that is implicitly are actually in the list
invoked when an object leave scope l The linked list-based list only uses enough
l The linked list destructor (~UnsortedList) must memory for the items in the list
clean up the object’s memory by deallocating all l Both have operations that are O(1)
the nodes in the list l Linked list’s MakeEmpty is O(N)

12
6/10/18

Comparing Implementations (cont.)

Table 3.2 Big-O Comparison of Sorted List Operations

13

You might also like