Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Cap3 PDF
Cap3 PDF
Departamento de informática
Campus de Segovia
Estructura de datos
Tema 3:
El TAD Lista lineal
• Conjunto de valores:
• Especificación formal:
unit LEstatic;
interface
const Max = ...; {especifica tamaño máximo lista}
type
tInfo = ...;{tipo de campo de información lista}
Lista = record
Elementos: array [1..Max] of tInfo;
Ultimo: integer
end;
Posicion = 0 .. Max;
procedure Inicia (var L: Lista);
function Localiza (L: Lista; E: tInfo): Posicion;
procedure Recupera (L: Lista; P:Posicion; var E: tInfo);
procedure Inserta (var L: Lista; P:Posicion; E: tInfo);
procedure SuprimeDir (var L: Lista; P: Posicion);
procedure Modifica (var L: Lista; P: Posicion; E: tInfo);
IMPLEMENTACIÓN ESTÁTICA
implementation
procedure Inicia;
begin
L.Ultimo := 0
end;
function Localiza;
var Q: Posicion; Lc: boolean;
begin
Q := 1; Lc := false;
while (Q <= L.Ultimo) and not Lc do
begin
Lc := L.Elementos [Q] = E;
if not Lc then Q := Q + 1
end;
if Lc then Localiza := Q
else Localiza := 0
end;
IMPLEMENTACIÓN ESTÁTICA
implementation (continúa...)
procedure Modifica;
begin
if L.Ultimo = 0 then Error (3)
else if (P > L.Ultimo) or (P < 1) then Error (1)
else
L.Elementos [P] := E
end;
end.
IMPLEMENTACIÓN DINÁMICA
procedure Inicia;
L
begin
L := nil
end;
function Localiza;
begin
while (L^.Sig < > nil) and (L^.Info < > E) do
L := L^.Sig;
if L^.Info < > E then Localiza := nil
else Localiza := L
end;
L^.Sig
E
L
TAD LISTA IMPLEMENTADO CON
LISTAS ENLAZADAS
implementation (continúa ...)
procedure Recupera;
begin
if not (L=nil) then
if (P < > nil) then E := P^.Info
end;
function Anterior (P: Ptr; L: Ptr): Ptr;
{El anterior de lista vacía, de dirección no
existente y del primer nodo de la lista,
devuelve nil}
begin
if (L = nil) or (P = nil) or (L = P) then
Anterior := nil
else begin
while (L^.Sig<>P) and (L^.Sig<>nil) do
L := L^.Sig;
if L^.Sig = P then Anterior := L
else Anterior := nil L L^.Sig = P
end {else}
end;
TAD LISTA IMPLEMENTADO CON
LISTAS ENLAZADAS
L
implementation (continúa ...)
procedure Inserta; {Inserta en L un nodo con el
var A: Ptrnodo; campo E, delante del nodo de
begin dirección P} A^.Sig = nil
new (A); L=A
A^.Info := E;
E
a) if (L = nil) then L := A {si L vacía}
else if P = L then {si P primer nodo}
begin L=P
b) A^.Sig := P; A
L := A
end E A^.Sig = P
c) else begin {si P es oto nodo, A entre anterior y P}
Anterior (P, L)^.Sig := A;
A^.Sig := P
end
end;
implementation
function EsVacia;
begin
EsVacia:= L=nil
end;
function Existe;
begin
if not EsVacia (L) then
begin
while (L^.Sig<>nil) and (L^.Info<>E) do
L := L^.Sig;
Existe := (L^.Info = E)
end;
else Existe := false
end;
IMPLEMENTACIÓN DEL TAD
LISTA ENLAZADA
implementation (continúa...)
function Siguiente;
begin
if EsVacia (L) or (P = nil) then
P P^.Sig
Siguiente := nil
else
Siguiente := P^.Sig
end;
function Ultimo;
begin
if EsVacia(L) then Ultimo := nil
else
begin
while (L^.Sig<>nil) do
L := L^.Sig;
L L^.Sig = nil
Ultimo := L;
end
end;
IMPLEMENTACIÓN DEL TAD
LISTA ENLAZADA
implementation (continúa...)
function Crea (E: tInfo): Ptr;
var N: Ptr;
begin N^.Sig = nil
N
new (N);
N^.Info := E; E
N^.Sig := nil;
Crea := N
end;
procedure Inserprim;
var A: Ptr; L
begin
A := Crea (E); A E
A^.Sig := L; L
L := A A
end;
E A^.Sig = L
IMPLEMENTACIÓN DEL TAD
LISTA ENLAZADA
implementation (continúa...)
procedure Inserfin;
var A: Ptr; L
begin
A := Crea (E); L
if EsVacia (L) then
L := A Ultimo(L)^.Sig=A E
else
Ultimo(L)^.Sig := A;
end;
procedure Suprime; L
var A: Ptr;
???
begin
L
A := Localiza(E, L);
if A<>nil then begin ???
if A = L then L := L^.Sig {primer nodo}
else Anterior (A, L)^.Sig := A^.Sig;
dispose(A)
end {if}
end;
IMPLEMENTACIÓN DEL TAD
LISTA ENLAZADA
implementation (continúa...)
procedure Anula;
begin
while not EsVacia (L) do
SuprimeDir (Ultimo(L), L)
end;
procedure Visualiza;
begin
while L< > nil do
begin
write(L^.Info,’ ’);
L := L^.Sig
end
end;
end.
TAD LISTA ORDENADA
else begin
A := Posinser (E, L);
if A = nil then begin{primera posición}
N^.Sig := L;
L := N
end;
else begin {posición intermedia}
L
N^.Sig := A^.Sig;
A
A^.Sig := N 12 29 36
A^.Sig
end 15 N^.Sig
end {else} N
end;
IMPLEMENTACIÓN DE
OPERACIONES LISTA ORDENADA
• Ahora la operación de búsqueda es más eficiente,
ya que para decidir si un elemento está o no en la
lista, basta con encontrar un elemento mayor.
Estructura de datos
Tema 3: TAD Pila
• Definición
• Especificación TAD Pila
• Implementación estática
• Implementación dinámica
• Aplicaciones de pilas
• Esquema recursivo
EL TAD PILA
• Especificación formal:
* Constructores
IMPLEMENTACIÓN ESTÁTICA
unit PEstatic;
interface
const Max = ...; {especifica tamaño máximo lista}
type
tInfo = ...;{tipo de campo de información lista}
Pila = record
Elementos: array [1..Max] of tInfo;
ultimo: integer
end;
procedure Inicia (var P: Pila);
function EsVacia (P: Pila): Boolean;
procedure Apilar (var P: Pila; E: tInfo);
procedure Desapilar (var P: Pila);
procedure Cima (P: Pila; var E: tInfo);
IMPLEMENTACIÓN ESTÁTICA
implementation
procedure Inicia;
begin
P.ultimo := 0
end;
function EsVacia;
begin
EsVacia:= P.ultimo = 0;
end;
procedure Error (n: integer);
{procedimiento oculto que sólo se ve en el
módulo}
begin
case n of
1: writeln (‘Error: Pila llena.’);
2: writeln (‘Error: Pila vacía.’);
end; {case}
readln
end;
IMPLEMENTACIÓN ESTÁTICA
implementation (continúa...)
procedure Apilar;
begin
if P.ultimo = Max then Error (1)
else
begin
P.ultimo := P.ultimo +1;
P.Elementos [P.ultimo] := E
end
end;
procedure Desapilar;
begin
if EsVacia (P) then Error (2)
else P.ultimo := P.ultimo - 1;
end;
procedure Cima;
begin
if EsVacia (P) then Error (2)
else E := P.Elementos [P.ultimo]
end;
IMPLEMENTACIÓN DINÁMICA
P
TAD PILA IMPLEMENTADO CON
LISTAS ENLAZADAS
unit PDinami;
interface
type
tInfo = ...; {tipo de campo de información lista}
Ptr = ^Nodo;
Nodo = record
Info: tInfo;
Sig: Ptr
end;
with aux^ do P
1 (1)
begin P
procedure Desapilar;
var aux: Ptr; aux aux
begin P
Pila (3)
if not EsVacia(P) then (1)
begin 15 ????
(1) aux := P; (2)
(2) P := P^.Sig; 8 8
(3) dispose(aux);
end
else writeln (‘Error: Pila vacía’)
end;
procedure Cima; P
begin 3
if not EsVacia(P) then
E := P^.Info 15
else writeln (‘Error: Pila vacía’) 8
end;
APLICACIONES DE LAS PILAS
a) Eliminar la recursividad.
• La recursividad se puede
implementar mediante una unidad
pila. Bajo esta perspectiva la
recursividad se convierte en un par
de bucles. El primero apila, el
segundo desapila y evalúa.
EJEMPLO: FACTORIAL DE n
function factorial (n: word): real;
var
pila: Ptr;
i: word; fac: real;
begin
Inicia (pila);
{primer bucle: apila las distintas llamadas}
for i := n downto 1 do Apilar (i, pila);
{Segundo bucle: resuelve las llamadas}
fac:=1 {caso base}
while pila < > nil do
begin
fac := Cima(pila) * fac;
Desapilar(pila)
end; function factorial (n: word): real;
begin
factorial := fac
if n = 0 then factorial :=1
end; else factorial := n*factorial (n-1)
end;
B) EVALUAR EXPRESIONES
ARITMÉTICAS
• Pasos que sigue el ordenador:
a) Transformar la expresión de infija
a postfija.
b) Evaluar la expresión postfija.
• Ejemplo inverso:
a) Postfija a infija:
Postfija: AB+CD*AB-/-
Infija: ((A+B)-((C*D)/(A-B)))
B (A+B) D (C*D)
A C (A+B)
(A+B)
B) EVALUAR EXPRESIONES
ARITMÉTICAS
B (A-B) ((C*D)/(A-B))
A (C*D) (A+B)
(C*D) (A+B)
(A+B)
((A+B)-((C*D) /(A-B)))
Estructura de datos
Tema 3:TAD cola
• Definición
• Especificación del TAD
• Implementaciones estáticas
• Implementación dinámica
• Esquemas recursivos
EL TAD COLA
- Una cola es una lista de elementos, en la
cual las eliminaciones se realizan por el
frente o principio de la cola, y los nuevos
elementos son añadidos por el otro
extremo, llamado fondo o final de la cola.
unit CEstatic;
interface
const Max = ...; {especifica tamaño máximo lista}
type
Posicion = 0..Max;
tInfo = ...; {tipo de campo de información lista}
Cola = record
Elementos: array [1..Max] of tInfo;
frente, final: Posicion
end;
procedure Inicia (var C: Cola);
function EsVacia (C: Cola): boolean;
procedure Primero (C: Cola; var E: tInfo);
procedure Encolar (var C: Cola; E: tInfo);
procedure Desencolar (var C: Cola);
IMPLEMENTACIÓN ESTÁTICA
implementation
procedure Inicia;
begin
C.frente := 1;
C.final := 0
end;
function EsVacia;
begin
EsVacia := C.final < C.frente
end;
procedure Primero;
begin
if not EsVacia (C) then
E := C.Elementos [C.frente]
end;
IMPLEMENTACIÓN ESTÁTICA
implementation (continúa...)
procedure Encolar;
begin
if not EsLlena (C) then
with C do
begin
final := final +1;
Elementos [final] := E
end
end;
procedure Desencolar;
begin
if not EsVacia (C) then
begin
for i:= 1 to C.final-1 do
C.Elementos [i] := C.Elementos [i+1];
C.final:=C.final-1;
end
end;
end.
IMPLEMENTACIÓN CIRCULAR
unit CCEstatic;
interface
const long = ...; {especifica tamaño máximo lista}
type
Posicion = 0..long;
tInfo = ...; {tipo de campo de información lista}
Cola = record
Elementos: array [1..long] of tInfo;
frente, final: Posicion
end;
procedure Inicia (var C: Cola);
function EsVacia (C: Cola): boolean;
function Primero (C: Cola): tInfo;
procedure Encolar (E: tInfo; var C: Cola);
procedure Desencolar (var C: Cola);
procedure Inicia;
begin
C.frente := nil;
C.final := nil
end;
function EsVacia;
begin
EsVacia := C.frente = nil
end;
procedure Primero;
begin
if not EsVacia (C) then
E := C.frente^.Info
end;
TAD COLA IMPLEMENTADO CON
LISTAS ENLAZADAS
implementation (continúa...)
procedure Desencolar;
var A: ptr;
begin
if not EsVacia (C) then
with C do
begin
A:= frente;
frente := frente^.Sig;
if frente = nil then final := nil;
dispose (A);
end
end;
TAD COLA IMPLEMENTADO CON
LISTAS ENLAZADAS
implementation (continúa...)
function Crea (E: tInfo): Ptr;
var A: ptr;
begin
new (A);
A^.Info:= E;
A^.Sig := nil;
Crea := A
end;
procedure Encolar;
var N: ptr;
begin
N := Crea (E)
with C do
begin
if EsVacia (C) then frente := N
else final^.Sig := N;
final := N;
end
end;
end.
ESQUEMAS RECURSIVOS CON
COLAS
uses Ucola;
...
procedure X (var C);
var elem: tInfo;
begin
if not EsVacia (C) then
begin
elem := Primero (C);
Desencolar (C, elem)
Desencolar (C);
Operación (elem);
X (C);
Encolar (C, elem);
end
end;
ESQUEMAS RECURSIVOS CON
COLAS
Ejemplo:
Dado el TAD Cola de enteros se pide
implementar una operación que invierta el
contenido de una Cola.
a) Escribir la sección interface de la unidad
cola.
b)
procedure Invertir (var C: Cola);
var elem: integer;
begin
if not EsVacia (C) then
begin
Desencolar (C, elem);
Invertir (C);
Encolar (C, elem)
end
end;