Metáfora del TDA(repaso)
• Conjunto de operaciones forman una pared
• forman una interfase entre los programas y la estructura de datos
¿Qué es una Lista?
Ejemplo 1. ARENAS ALICEA, ALEXIS
2. CASANOVA DEL MORAL, LISA R
3. COLON VELEZ, MIGUEL A
4. GAMBOA NIEVES, EXEL
5. HERNANDEZ VIERA, MARIAN
6. JAIME COLLAZO, ASTRID M
7. MEDINA RIVERA, LUIS A
8. MUNOZ HERNANDEZ, JOSE L
9. NAVARRO LOPEZ, AIDA Y.
10. PASSAPERA SANCHEZ, LIANETTE
11. QUILES LOPEZ, JUAN
12. REYES COLON, JUAN C
13. REYES TORRES, JENNY
14. ROSADO MILLAN, ARELIS
15. SANTIAGO APONTE, MARIA M
16. TORRES VELAZQUEZ, DORCI LEE
Abstracción
Características que tiene toda lista:
• tiene algo o está vacía
si tiene algo...
• Tiene una cantidad finita de elementos
• Tiene un primer elemento
• tiene un último elemento
• cada elemento tiene una posición
• cada elemento tiene un sucesor (excepto el último)
• cada elemento tiene un predecesor (excepto el primero)
TDA Lista
Una Lista es una colección lineal de objetos con las siguientes operaciones:
• crear una lista vacía
• detrminar si la lista está vacía
• determinar cantidad de elementos
• añadir item en determinada posición
• elininar iten de determinada posición
• ver el item en una posición dada
Interfacesuna manera de representar un TDA en Java
public interface ListInterface {
public boolean isEmpty();
public int size();
public void add(int index, Object item);
public Object get(int index) ;
public void remove(int index);
public void removeAll();
} // end ListInterface
¿Qué falta?
• Estructura de Datos– hay distintas opciones
– podemos seleccionar un arreglo para guardar los items y un entero para saber cuantos items hay
• Algoritmos– dependen de la ED que se haya seleccionado
Una implantación con arreglos
public class ListArrayBased implements ListInterface {
private static final int MAX_LIST = 50;
private Object items[]; // an array of list items
private int numItems; // number of items in list
public ListArrayBased() {
items = new Object[MAX_LIST];
numItems = 0;
} // end default constructor
public boolean isEmpty() {return (numItems == 0);}
public int size() {return numItems;} // end size
public void add(int index, Object item) {
if (numItems <= MAX_LIST) {
if (index >= 1 && index <= numItems+1) {
for (int pos = numItems; pos >= index; pos--) {
items[translate(pos+1)] = items[translate(pos)];
} // end for
items[translate(index)] = item;
numItems++;
}
} // end if
} // end if
} //end add
public Object get(int index) { if (index >= 1 && index <= numItems) { return items[translate(index)]; } // end if } // end get public void remove(int index) { if (index >= 1 && index <= numItems) { for (int pos = index+1; pos <= size(); pos++) { items[translate(pos-1)] = items[translate(pos)]; } // end for numItems--; } // end if } //end remove} // end ListArrayBased
Ilustración de add(3,44)
k
numItems
12 3 19 100 ... 5 10 ¿? ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 19 100 ... 5 10 ¿? ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 19 100 ... 5 10 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 19 100 ... 5 10 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 19 100 ... 5 5 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 19 19 ...100 5 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 44 19 ...100 5 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Ilustración de add(3,44)
k
numItems
12 3 44 19 ...100 5 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA 44
Sumar 1
Ilustración de add(3,44)
K+1
numItems
12 3 44 19 ...100 5 10 ... ¿?
0 1 2 3 ... K-1 MAX
Índices del arreglo
1 2 3 4 k
Posiciones del TDA
Ventajas y Desventajasde la implantación de listas con arreglos
• Ventajas–relativamente fácil
–ED arrego es parecido a TDA lista
• Desventajas–se llena
–hay que estar rodándolo
Listas enlazadasTDA Nodo
Un Nodo es un par información y vínculo al próximo nodo con las siguientes operaciones:– constructor
– setItem(x): pone x en el campo de información
– setNext(n): pone n en el vínculo al próximo
– getItem(): devuelve campo de información
– getNext(): devuelve referencia al próximo
info
Listas enlazadasImplantación de Nodo
public class Node {
private Object item;
private Node next;
public Node(Object newItem) {
item = newItem;
next = null;
} // end constructor
public Node(Object newItem, Node nextNode) {
item = newItem;
next = nextNode;
} // end constructor
public void setItem(Object newItem) { item = newItem; } // end setItem
public Object getItem() { return item; } // end getItem
public void setNext(Node nextNode) { next = nextNode; } // end setNext
public Node getNext() { return next; } // end getNext} // end class Node
public class ListReferenceBased implements ListInterface {
// reference to linked list of items
private Node head;
private int numItems; // number of items in list
//c ListReferenceBased(), isEmpty(), size()
private Node find(int index) {
Node curr = head;
for (int skip = 1; skip < index; skip++) {
curr = curr.getNext();
} // end for
return curr;
} // end find
public Object get(int index) {
if (index >= 1 && index <= numItems) {
// get reference to node, then data in node
Node curr = find(index);
Object dataItem = curr.getItem();
return dataItem;
}
else {
System.out.println(
"List index out of bounds exception on get");
} // end if
} // end get
public void add(int index, Object item) { if (index >= 1 && index <= numItems+1) { if (index == 1) { // insert the new node containing item at // beginning of list Node newNode = new Node(item, head); head = newNode; } else { Node prev = find(index-1); // insert the new node containing item after // the node that prev references Node newNode = new Node(item, prev.getNext()); prev.setNext(newNode); } // end if numItems++; } else { System.out.println( "List index out of bounds exception on add"); } // end if } // end add
public void remove(int index) {
if (index >= 1 && index <= numItems) {
if (index == 1) {
// delete the first node from the list
head = head.getNext();
}
else {
Node prev = find(index-1);
// delete the node after the node that prev
// references, save reference to node
Node curr = prev.getNext();
prev.setNext(curr.getNext());
} // end if
numItems--;
} // end if
else {
System.out.println("List index out of bounds exception on remove");
} // end if
} // end remove
Análisis de ambas implantaciones
Con Arreglos.
Suponer que hay N elementos en la lista
• añadir(k,x)– hay que rodar los que están de k en adelante
– el peor caso es cuando k=1
– en ese caso hay que mover N cosas
– hay otras 4 instrucciones fuera del ciclo
– total de instrucciones en el peor caso: N+4
Análisis de ambas implantaciones
Con Arreglos
• Delete(k)– hay que rodar los elementos desde después de
la posición k
– el peor caso es k=1
– en ese caso hay que mover N-1 cosas
– hay otras 2 instrucciones fuera del ciclo
– total de instrucciones en el peor caso: N+1
Análisis de ambas implantaciones
Con listas enlazadas
• Add(k,x)– hay moverse de nodo en nodo hasta la posición k
– el peor caso es k=n
– en ese caso hay que moverse N-1 veces
– hay otras 3 instrucciones fuera del ciclo
– total de instrucciones en el peor caso: N+2