Propedéutico de Programación Coordinación de Ciencias Computacionales Semana 4, Segunda Parte Dra. Pilar Gómez Gil Versión 1. 24.06.08 http://ccc.inaoep.mx/~pgomez/cursos/programacion/
Chapter 3 ADT Unsorted List (continuación)
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
Representación abstracta de una lista 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 null
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
Be sure you understand the differences among location, *location, and location->info Lo que está pintado de azul fuerte es lo que regresa Cada instrucción
Private data for the Unsorted List ADT, linked-list implementation private: NodeType* listdata; int length; NodeType* currentpos; ; List with two items
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
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
bool Unsortedtype::IsFull() const { NodeType* location; try { location = new NodeType; delete location; return false; catch (std::bad_alloc exception) { return true; What about MakeEmpty?
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?
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 ); 13 Linked Implementation
Linked Implmentation
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 15
We forgot something: We must put NULL in the Next position of the first node 16
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?
Now we must put the two parts together--carefully!
Liked Implementation These steps must be done in this order! Why?
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++;
How do you delete an item? Find the item Remove the item 2 posibilidades: Borrar el primero Borrar uno enmedio
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--;
ResetList and GetNextItem What was currentpos in the arraybased implementation? What would be the equivalent in a 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
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
Ver unsorted.h (implementación ligada) Ver unsorted.cpp (implementación ligada)