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

Lesson 2

This document discusses unsorted linked lists and pointers. It covers: 1) The key aspects of an unsorted linked list including nodes containing data and next pointers, and operations like putItem, deleteItem, and iterators. 2) How pointers work at the logical level as an address and at the implementation level using dynamic allocation with new and delete. 3) An example implementation of an unsorted linked list using nodes with dynamic memory allocation and next pointers to link the nodes together.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lesson 2

This document discusses unsorted linked lists and pointers. It covers: 1) The key aspects of an unsorted linked list including nodes containing data and next pointers, and operations like putItem, deleteItem, and iterators. 2) How pointers work at the logical level as an address and at the implementation level using dynamic allocation with new and delete. 3) An example implementation of an unsorted linked list using nodes with dynamic memory allocation and next pointers to link the nodes together.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter 3

ADT Unsorted List


Lists
l A list is a homogeneous collection of elements
with a linear relationship between elements
l Linear Relationship: Each element except the
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
l Unsorted List: A list in which data items are
placed in no particular order
l Sorted List: A list that is sorted by the keys of
the list items; there is a semantic relationship
among the keys of the items in the list
l Key: The attributes used to determine the
logical order of the list
Unsorted List: Operations
l Constructor: May make empty list or take some
initial elements
l Transformers: PutItem, DeleteItem, MakeEmpty
l Observers: IsFull, GetLength
l Iterators: ResetList, GetNextItem
What is a generic data type?
l A type for which the operations are defined but
the types of the items being manipulated are
not defined
l Our Unsorted List ADT simulates this by using a
user-defined class called ItemType that defines
the member functions we need
Unsorted List: Application Level
l Unsorted lists seem to provide a few, limited
operations
l But it provides all the tools we need to write
more specialized functions
l Printing list items, reading items from a file, and
so on can all be written using this limited set of
operations
Unsorted List: Implementation
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
Array vs. Linked List

Figure 3.1 Comparison of Array and Linked Structure


Implementation: Constructors
l Class Constructor: A special member function
that is implicitly invoked when a class object is
created
- Used to initialize objects and allocate
resources
l For UnsortedType, the constructor sets the
length to 0
l No resources need to be allocated because the
size of the array is static
Class Constructor Rules
1) A constructor cannot return a function value and has
no return value type
2) A class may have several constructors; the compiler
chooses the appropriate constructor by the number
and types of parameters used
3) Constructor parameters are placed in a parameter list
in the declaration of the class object: SomeClass
anObject(param1, param2);
4) The parameterless constructor is the default
constructor
5) A class must have a default (parameterless)
constructor in order to create arrays of that class
Implementation: Observers
l IsFull and GetLength are straightforward
l GetItem requires a linear search through the list
- Use ItemType.CompareTo to check equality
- Use bool &found reference parameter to indicate
success to the user
- Return a copy of the found item
Implementation: Transformers
l PutItem: Insert item at the end of the list,
increment length
l DeleteItem: Linear search to find item, but how
to remove it?
- If the item is at the end of the list, just reduce the
length of the list by one
- But what about if it’s at the beginning?
Implementation: DeleteItem
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
DeleteItem: Move or Swap?

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
l The field currentPos indicates the current
position of iteration in the list
l GetNextItem increments currentPos and
returns the item at that position
l ResetList must set currentPos to the first
item’s predecessor
- For arrays, that’s -1
Unsorted List: Test Plan
l Preconditions and postconditions determine the
black-box tests
l Code of functions determines clear-box tests
l We make sure the tests touch upon edge
cases, such as the first and last items in the list,
or a list with only one item
Pointer Types: Logical Level
l A pointer variable contains the memory
address of another variable
l They are used for indirect addressing of data
and for dynamic allocation of memory
l Pointers are declared using an asterisk:
int* intPointer;
Pointer Operators
l The prefix ampersand (&) or “address of”
operator returns the address of a variable:
- int alpha = 10;
- intPointer = α
- intPointer now contains alpha’s memory address
l The asterisk dereference operator (*) denotes
the variable to which a pointer points:
- *intPointer = 25; // alpha is now 25
Dynamic Allocation
l Dynamic Allocation: Allocation of memory
space for a variable at run time, as opposed to
static allocation at compile time
l Dynamic allocation creates variables on the
heap (or free store), a section of memory
reserved for dynamic allocation
Dynamic Allocation (cont.)
l Dynamic allocation uses the keyword new:
- int* ptr = new int;
l new returns a pointer to the newly allocated int
on the heap, and the value can only be
accessed via this pointer
l Pointers can point to nothing using NULL
l If no memory is available on the heap, new
returns NULL
Memory Leak
l A memory leak is the loss of available memory
space that occurs when some dynamically
allocated memory is never deallocated
l Dynamically allocated memory that can’t be
accessed is called garbage
Memory Leak Example
float* money = new float;
*money = 33.46;
float* myMoney = new float;
Memory Leak Example (cont.)
This copies the value pointed to by money into the
memory pointed to by myMoney:
*myMoney = *money;
Memory Leak Example (cont.)
This makes myMoney point to the same address
that money points to:
myMoney = money;
Memory Leak Example (cont.)
The memory cell originally used by myMoney is
now inaccessible. Since there’s no way to collect
the garbage, it is a small memory leak.
The Delete Operator
l The delete operator deallocates the memory
pointed to by the argument
l Using delete myMoney would safely clean up
the memory allocated to myMoney
l C++ requires manual memory management
Pointers: Application Level
l The name of an array variable when used
without brackets is a pointer constant
l Pointers can be used with constant types,
allowing objects to link to each other
l If myPtr is a pointer to an object, the fields of
the object are accessed using the arrow
operator: myPtr->field
Pointers: Implementation Level
l Pointers and dynamic memory are thankfully
handled entirely by the operating system,
compiler, and run-time system
l Except you must remember to delete
dynamically allocated memory when you are
finished with it!
UnsortedType as a Linked List
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
Nodes

Figure 3.11 Node Terminology


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

Figure 3.9 Putting in the First Element


Building the Chain

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
Length and Linked Lists
l For array-based lists, the length field must be
present in order to define the extent of the list
within the array
l Linked lists don’t have this restriction
l Instead of a field, GetLength could walk the list
and count the number of nodes
Iterators
l The array-based implementation used
currentPos, an array index
l Linked lists use a pointer to a node instead
l GetNextItem advances it: currentPos->next
l ResetList sets it to NULL
- GetNextItem checks if it’s NULL and sets it to the
first item of the list
PutItem
1) Create a new node
2) Set the node’s info to the input data
3) Set the node’s next pointer to the listData, the
first item in the list
4) Set listData to point to the new node

Order matters! Doing step 4 before step 3 would


lead to a memory leak of the rest of the list.
PutItem (cont.)
void UnsortedType::PutItem (ItemType item)
// Pre: list is not full and item is not in list.
// Post: item is in the list; length has been incremented.
{
NodeType<ItemType>* location;
// create a new node and fill it
location = new NodeType<ItemType>;
location->info = item;
location->next = listData;
// the new node becomes head of the list
listData = location;
length++;
}
PutItem: Empty List

Figure 3.16 Putting an Item into an Empty List


Constructor
l Largely unchanged
l Set length to 0
l Set the external pointer to NULL
IsFull
l Linked lists don’t have an explicit size limit
l New nodes can be allocated until there is no
more memory to use
l When this occurs, new will throw a bad_alloc
exception
l IsFull uses a try-catch block to allocate a node
and returns true if a bad_alloc is thrown
IsFull (cont.)
bool UnsortedType::IsFull() const
// Returns true if there is no room for another ItemType
// on the free store; false otherwise.
{
NodeType* location;
try
{
location = new NodeType;
delete location;
return false;
}
catch(std::bad_alloc exception)
{
return true;
}
}
MakeEmpty
l MakeEmpty must deallocate each node
individually in order to empty the list
l This is accomplished using a while loop
l Iteration starts at listData, the head of the list,
and continues using listData->next
l Iteration stops when listData is NULL
GetItem
l The algorithm is unchanged: Linear search
through the list to find the desired item
l In fact, the implementation is largely
unchanged; it just needs to use pointers instead
of array indices
GetItem (cont.)

Figure 3.17 Retrieving an item in an unsorted linked list (a) Get Kit (b) Get Lila
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)
DeleteItem (cont.)

Figure 3.18 Deleting an interior node and deleting the first node (a) Delete Lila
(b) Delete Kate
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
outside the time of their blocks
Class Destructors
l An object is deallocated when it leaves scope,
but any data it points to is not – memory leak!
l A class destructor is a method that is implicitly
invoked when an object leave scope
l The linked list destructor (~UnsortedList) must
clean up the object’s memory by deallocating all
the nodes in the list
Comparing Implementations
l The array-based list allocates enough memory
for the max list size, no matter how many items
are actually in the list
l The linked list-based list only uses enough
memory for the items in the list
l Both have operations that are O(1)
l Linked list’s MakeEmpty is O(N)
Comparing Implementations (cont.)

Table 3.2 Big-O Comparison of Sorted List Operations

You might also like