Propedéutico de Programación

Similar documents
ADT Unsorted List. Outline

Propedéutico de Programación

What is a List? elements, with a linear relationship. first) has a unique predecessor, and. unique successor.

Definition of Stack. 5 Linked Structures. Stack ADT Operations. ADT Stack Operations. A stack is a LIFO last in, first out structure.

Propedéutico de Programación

Propedéutico de Programación

Chapter 4. ADT Sorted List

moretosearch = (location < length);

Propedéutico de Programación

ADT Sorted List Operations

ADTs Stack and Queue. Outline

CS 308 Data Structures Spring Dr. George Bebis Final Exam

Default Route de la configuración en el EIGRP

Chapter 5. ADTs Stack and Queue

ADTs Stack and Queue. Outline

template<class T> T TreeNode<T>:: getdata() const { return data; }//end getdata

Data Structures and Algorithms

OCTOBEAM. LED Lighting Effect USER MANUAL / MANUAL DE USUARIO

Common Misunderstandings from Exam 1 Material

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CSCE 110 PROGRAMMING FUNDAMENTALS

Extra Credit: write mystrlen1 as a single function without the second parameter int mystrlen2(char* str)

An Introduction to Queues With Examples in C++

Tema 5. Ejemplo de Lista Genérica

CS302 - Data Structures using C++

FORMAS DE IMPLEMENTAR LOS OYENTES. A).- El oyente en una clase independiente con el constructor con un argumento y usando el método getactioncommand.

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Lecture Notes CPSC 122 (Fall 2014) Today Quiz 7 Doubly Linked Lists (Unsorted) List ADT Assignments Program 8 and Reading 6 out S.

CSCE 110 PROGRAMMING FUNDAMENTALS

ICOM 4035 Data Structures. Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department

Propedéutico de Programación

Table ADT and Sorting. Algorithm topics continuing (or reviewing?) CS 24 curriculum

Iterator: A way to sequentially access ( traverse ) each object in a container or collection. - Access is done as needed, not necessarily at once.

Anexos. Diseño y construcción de un puente grúa automatizado de precisión

Assignment of Objects

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

CS302 - Data Structures using C++

Link-Based Implementations. Chapter 4

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

Tutorial 3 Q&A. En la pregunta 7 de la sección 2.2 el cual dice: 7. Prove the domination laws in Table 1 by showing that: a)a U = U b)a =

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

PROGRAMACIÓN ORIENTADA A OBJETOS

CSC 210, Exam Two Section February 1999

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

C++_ MARKS 40 MIN

b) Use one of your methods to calculate the area of figure c.

Chapter 8. Binary Search Trees. Fall 2013 Yanjun Li CISC Trees. Owner Jake. Waitress Waiter Cook Helper Joyce Chris Max Len

EMTECH_3P_A_1_v4. Descripción de la placa.

void insert( Type const & ) void push_front( Type const & )

ADT: Design & Implementation

Linked List using a Sentinel

How can we improve this? Queues 6. Topological ordering: given a sequence of. should occur prior to b, provide a schedule. Queues 5.

Single user Installation. Revisión: 13/10/2014

Class and Function Templates

RISC Processor Simulator (SRC) INEL 4215: Computer Architecture and Organization Feb 14, 2005

CSI33 Data Structures

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

EECE.3220: Data Structures Spring 2017

IntesisBox PA-RC2-xxx-1 SANYO compatibilities

Special Member Functions

Querying Microsoft SQL Server 2014

Lecture 10 March 4. Goals: hashing. hash functions. closed hashing. application of hashing

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

Chapter 17: Linked Lists

Lab 2: ADT Design & Implementation

CS 2604 Homework 1 C++ Review Summer I 2003

CS302 - Data Structures using C++

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

C:\Temp\Templates. Download This PDF From The Web Site

Objects Managing a Resource

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

DM6. User Guide English ( 3 10 ) Guía del usuario Español ( ) Appendix English ( 13 ) DRUM MODULE

Create Extensions App inventor 2 Build Extensions App Inventor, easy tutorial - Juan Antonio Villalpando

Data Structures And Algorithms

CS212 - COMPUTATIONAL STRUCTURES AND ALGORITHMS

Chapter 17: Linked Lists

INHERITANCE: CONSTRUCTORS,

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

PROBLEM 1 : (Vocabulary: 8 points) For each of the words/phrases below, circle the denition that is the best description as it pertains in the context

CS302 - Data Structures using C++

8 Binary Search Trees

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

SCJ2013 Data Structure & Algorithms. Queue. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

! A data type for which: ! An ADT may be implemented using various. ! Examples:

PRÁCTICO 1: MODELOS ESTÁTICOS INGENIERÍA INVERSA DIAGRAMAS DE CLASES

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Allocation & Efficiency Generic Containers Notes on Assignment 5

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

INTERNATIONAL EDITION. Problem Solving with C++ Data Abstraction & SIXTH EDITION. Walls and Mirrors. Frank M. Carrano Timothy Henry

INTOSAI EXPERTS DATABASE

Chapter 18: Stacks And Queues

Overview: Multicore Architectures

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Call The Project Dynamic-Memory

Homework Assignment #3

An abstract tree stores data that is hierarchically ordered. Operations that may be performed on an abstract tree include:

IntesisBox TO-RC-xxx-1 Toshiba compatibilities

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

Transcription:

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)