Propedéutico de Programación Coordinación de Ciencias ...pgomez/cursos/programacion/... · How...
Transcript of Propedéutico de Programación Coordinación de Ciencias ...pgomez/cursos/programacion/... · How...
Propedéutico de Programación
Coordinación de Ciencias
Computacionales
Semana 4,
Segunda Parte
Dra. Pilar Gómez Gil
http://ccc.inaoep.mx/~pgomez/cursos/programacion/
Versión 1. 24.06.08
Chapter 3 ADT Unsorted List
(continuación)
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Implementación usando apuntadores
• Se puede construir una lista ligada a través del uso de apuntadores y creación dinámica de espacios para almacenar los elementos conforme van apareciendo.
• Para esto, cada elemento deberá contener información sobre cual es el elemento siguiente de la lista
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Representación abstracta de una lista
contenido
Referencia a donde esta el siguiente
contenido
contenido
Referencia a donde esta el siguiente
contenido contenido
Referencia a donde esta el siguiente
contenido
contenido
Referencia a donde esta el siguiente
contenido Lista:
null Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Construcción de listas
• Referencia significa la dirección de memoria donde está almacenado el siguiente elemento. Entonces este campo no contiene realmente un valor, sino una dirección donde se encuentra
• “nulo” significa que esa referencia ya no apunta a nadie mas
• Si una lista esta vacía, entonces vale “nulo”
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implementation
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implementation
Be sure you
understand the
differences among location,
*location, and location->info
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Lo que está pintado de “azul fuerte” es lo que regresa Cada instrucción
Linked Implementation • Private data for the Unsorted List ADT,
linked-list implementation
private: NodeType* listData; int length; NodeType* currentPos; };
List with two items
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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?
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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?
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
13
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 );
}
}
}
Linked Implementation
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implmentation
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
15
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
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
16
Linked Implementation
We forgot something: We must put NULL in the Next position of the first node
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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?
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implementation
Now we must put the two parts together--carefully!
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Liked Implementation
These steps
must be done in
this order! Why?
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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;
location->info = item;
location->next = listData;
listData = location;
length++;
}
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implementation How do you delete an item?
Find the item
Remove the item
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
2 posibilidades: Borrar el primero Borrar uno en- medio
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--;
}
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
Linked Implementation
• ResetList and GetNextItem
What was currentPos in the array-
based implementation?
What would be the equivalent in a
linked implementation?
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
UML Diagram
Note the
differences between the UML Diagrams
for the two
implementations
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
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
Tomado de: Dale, N. Weems, C++ Plus Data Structures 4th. Ed. 2007 Instructor material, © Jones & Barlett Publishers
• Ver unsorted.h (implementación ligada)
• Ver unsorted.cpp (implementación ligada)