Una pila es una estructura de datos en la cual el acceso est� limitado al elemento m�s recientemente insertado y solamente puede crecer y decrecer por uno de sus extremos.
Las pilas se denominan tambi�n estructuras LIFO (Last-In-First-Out), porque su caracter�stica principal es que el �ltimo elemento en llegar es el primero en salir.
En todo momento, el �nico elemento visible de la estructura es el �ltimo que se coloc�.
Se define el tope de la pila como el punto donde se encuentra dicho elemento.
En una pila, las tres operaciones naturales de insertar, eliminar y obtener el dato, se renombran por push, pop e info.
Interfaz
Como existen diferentes formas de implementar una Pila ( vectores, listas enlazadas ) la primera parte del dise�o est� constituida por la declaraci�n de una interfaz, con las operaciones b�sicas.
interface Pila
{
void push(Object x);
void pop( ) throws Exception;
Object info( ) throws Exception;
boolean esVacia( );
void vaciar( );
}
M�todos
push( x ) --> Inserta x
pop( ) --> Elimina el �ltimo elemento insertado
info( ) --> Retorna el �ltimo elemento insertado
esVacia( ) --> Retorna true si no existen elementos ; false en caso contrario
vaciar( ) --> Elimina todos los elementos
Implementaci�n con Lista Enlazada
class Nodo
{
public Object dato;
public Nodo siguiente;
public Nodo(Object elemento, Nodo sgte)
{
this.dato = elemento;
this.siguiente = sgte;
}
public Nodo(Object elemento)
{
this(elemento,null);
}
}
class PilaLi implements Pila
{
private Nodo tope;
public PilaLi( )
{
tope = null;
}
public boolean esVacia( )
{
return tope == null;
}
public void vaciar( )
{
tope = null;
}
public void push(Object x)
{
tope = new Nodo(x,tope);
}
public Object info( ) throws Exception
{
if ( esVacia( ) )
throw new Exception("info");
return tope.dato;
}
public void pop( ) throws Exception
{
if ( esVacia( ) )
throw new Exception("pop");
tope = tope.siguiente;
}
}
Programa de prueba
class TestPila
{
public static void main(String arg[ ])
{
Pila p = new PilaLi( );
for(int i = 0; i < 10; i++)
p.push( new Integer(i+1) );
System.out.print("\n\tContenido : ");
try
{
for( ; ; )
{
System.out.print(" " + p.info( ) );
p.pop( );
}
}
catch(Exception e){ }
System.out.println( );
}
}
Ejercicio resuelto
Implementar un m�todo que imprima un n�mero en cualquier base, usando un m�todo
que use pilas.
Soluci�n
import java.io.*;
class test2
{
public static void convertirBase(int numero , int base)
{
Pila p = new PilaLi( );
while(numero != 0)
{
p.push(new Integer( numero % base ) );
numero /= base;
}
try
{
for(;;)
{
System.out.print(p.info( ) );
p.pop( );
}
} catch(Exception e) { }
}
public static void main(String arg[ ])
{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
int num,base;
boolean seguir = true;
while(seguir)
{
try
{
System.out.print("\n\tIngrese un numero : ");
num = Integer.parseInt(in.readLine( ) );
System.out.print("\tIngrese la nueva base : ");
base = Integer.parseInt(in.readLine( ) );
System.out.print("\tEl numero " + num + " en base " + base + " es : ");
convertirBase(num,base);
System.out.print("\n\tQuiere seguir : s/n : ");
String resp = in.readLine( );
if (resp.charAt(0) == 's') seguir = true;
else seguir = false;
}
catch (Exception e)
{
System.out.println("\tError de entrada : " + e);
}
}
}
}
salida del programa