Metodo_Principal.java (Metodo Principal)
JAVA:
import java.io.*;
public class Metodo_Principal{
//Declaramos el metodo principal
public static void main (String args[])throws IOException {
BufferedReader entrada = new BufferedReader (new InputStreamReader(System.in));
int Espacios = 0;
char Resp, op;
String aux;
//--- Imprimir Menu ---- \\
System.out.println("\n :: XROM RELOADED :: 19/07/07 \n");
System.out.print("\t Cuantos espacios quiere en la Pila (entre 3 y 30 recomendable)? :");
Espacios = Integer.parseInt(entrada.readLine());
Pila Ejecutar = new Pila(Espacios);
System.out.println("\n\n\t --- //---- Menu Pila------\\\\---- \n");
do {
System.out.println("\n\n1.- Imprimir Pila"); // Mostrar
System.out.println("2.- Agregar Elemento a la pila"); // Push
System.out.println("3.- Quitar Elemento de la pila"); // Pop
System.out.print("\n\n Elija una Opcion : ");
aux = entrada.readLine();
op = aux.charAt(0);
//---- Elegir opcion ---\\
switch (op) {
case '1':
Ejecutar.Imprimir();
break;
case '2':
Ejecutar.Push();
break;
case '3':
Ejecutar.Pop();
break;
default:
System.out.println("opcion fuera de rango !!");
} // Fin del switch
System.out.print("Desea hacer otra operacion ?? S / N ");
aux = entrada.readLine();
Resp = aux.charAt(0);
} while (Resp == 'S' Resp == 's');
System.out.println(" Garcias por utilizar este programa.. ");
System.out.println("\t para mas informacion en :: WWW.XROMRELOADED.TK ::");
} // Fin del metodo main
} // Fin de la calse
Pila.java (Clase y Metodos)
JAVA:
// Libreria necesaria para introducir datos desde el Teclado
import java.io.*;
// Inicio de la Clase Pila
public class Pila {
//----- Atributos de la pila ------\\
public int Pila []; // Estructura de la pila
public int Top, Max , Elem; // variables para la pila
//Top : El Tope de la pila , referencia al ultimo elemento que esta en la pila
//Max : Maximo de espacios que tiene la pila
//Elem : Elemento que se agrega a la pila (Tecleado por el usuario)
public char Resp; // Variables para SubMenus.
public String aux;
//----- Contructor -------\\
public Pila (int Espacios){ // se recibe como parametro los Espacios de la pila
Pila = new int [Espacios]; // Asignamos los espacios en la Pila
Max = Pila.length - 1;
Top = -1; // Top se declara como -1 como referencia a que no existen datos en la pila
} // fin del constructor
//----- Metodos de la pila -------\\
// Metodo Imprimir
public void Imprimir () {
for (int n = 0 ; n <= Max ; n++ ) { System.out.println(n + ".- " + Pila [n]);
}
} // Fin del Metodo Imprimir
// Metodo Push
public void Push ( ) throws IOException { // Metodo para ingresar datos ...
BufferedReader entrada = new BufferedReader (new InputStreamReader(System.in));
do {
// if (1)
if(Top != Max) { // Si la pila No esta llena ....
// Se puede agregar un nuevo dato a la pila ....
System.out.print("\t Ingrese un numero entero : ");
Elem = Integer.parseInt(entrada.readLine());
Top ++; // Se incrementa Top como referencia de que se agrego un nuevo dato
Pila[Top] = Elem; // Se agrega el nuevo elemento a la pila
// if (1.1)
if (Top == Max) { // Si la pila quedo llena entoces ...
// Imprimir mensaje
System.out.print("\n La Pila a quedado llena !! ");
// con esta variable detenemos el bucle do - while
Resp = 'N';
} // Fin del if (1.1)
} else {
System.out.println("\n Pila llena !! Imposible introducir un valor a la pila");
Resp = 'N'; // detenemos el bucle
} // Fin del if (1)
// if (2)
if (Resp != 'N') {
// Si es diferente de No , entoces seguir preguntado si se desea introducir mas datos
System.out.print("Desea introducir un dato mas ??");
aux = entrada.readLine();
Resp = aux.charAt(0);
} // Fin del if (2)
} while (Resp == 'S' Resp == 's'); // Continuar ciclando simpre y cuando sea Resp = 's'
} // Fin del Metodo Push
// Metodo Pop
public void Pop () {
if(Top != -1) { // Si la pila no esta vacia entonces ....
System.out.println("Se borro el Dato : " + Pila[Top]);
// Eliminar dato
Pila[Top] = 0; // remplaza el valor por un cero (Eliminado)
Top --; // Top se reduce para decir que un elemento se borro
} else { // De lo contrario imprime .."que la pila esta vacia"
System.out.println("Pila Vacia... Imposible Eliminar");
} // fin del if
} //Fin del Metodo Pop
} // Fin de la Clase Pila
2- PROGRAMA_PILAS
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;
}
}
interface Pila
{
void push(Object x);
void pop() throws Exception;
Object info() throws Exception;
boolean esVacia();
void vaciar();
}
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);
}
}
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);
}
} // fin while
} // fin main
}
class TestPila
{
public static void main(String arg[])
{
Pila p = new PilaLi();
for(int i = 0; i < pilaaux =" duplicar(pila);" e =" pilaAux.tope();" pila2 =" (Pila)pila.getClass().newInstance();" pilaaux =" (Pila)pila.getClass().newInstance();" e =" pila.tope();" e =" pilaAux.tope();" pilaaux =" new" colaaux =" duplicar(cola);" e =" colaAux.primero();" cola2 =" (Cola)cola.getClass().newInstance();" e =" pilaAux.tope();">
IMPLEMENTACIONES
package pilaBasadaLista;
import pilaException.*;
import listaException.*;
import listaSimpleEnlazada.*;
public class Pila implements pilaInterface.Pila {
private Lista lista;
public Pila() {
lista = new Lista();
}
public boolean vacia() {
return lista.vacia();
}
public Object tope() throws PilaVaciaException {
if (vacia()) throw new PilaVaciaException();
try {
return lista.recupera(lista.primero());
} catch (ListaException e) {
System.err.println("Error interno de la Pila: "+e);
return null;
}
}
public void push(Object elemento) {
try {
if (vacia()) lista.inserta(lista.fin(),elemento);
else lista.inserta(lista.primero(),elemento);
} catch (ListaVaciaException e) {
System.err.println("Error interno de la Pila");
}
}
public void pop() throws PilaVaciaException{
if (vacia()) throw new PilaVaciaException();
try {
lista.suprime(lista.primero());
} catch (ListaException e) {
System.err.println("Error interno de la Pila");
}
}
} // fin class Pila
*************************************
IMPLEMENTACION CON VECTORES
package pilaContigua;
import pilaException.*;
public class Pila implements pilaInterface.Pila {
private static int max = 100;
private Object elementos[];
private int tope;
public Pila() {
elementos = new Object[max];
tope=max;
}
public boolean vacia() {
return (tope==max);
}
**********************************
public Object tope() throws PilaVaciaException {
if (vacia()) throw new PilaVaciaException();
return elementos[tope];
}
public void push(Object elemento) {
tope--;
elementos[tope]=elemento;
}
public void pop() throws PilaVaciaException{
if (vacia()) throw new PilaVaciaException();
tope++;
}
} // fin class Pila
IMPLEMENTACIÓN CON APUNTADORES
package pilaSimpleEnlazada;
import pilaException.*;
public class Pila implements pilaInterface.Pila {
class Celda {
Object elemento;
Celda sig;
}
private Celda pila;
public Pila() {
pila = null;
}
public boolean vacia() {
return (pila==null);
}
public Object tope() throws PilaVaciaException {
if (vacia()) throw new PilaVaciaException();
return pila.elemento;
}
public void push(Object elemento) {
Celda aux = new Celda();
aux.elemento = elemento;
aux.sig = pila;
pila = aux;
}
public void pop() throws PilaVaciaException{
if (vacia()) throw new PilaVaciaException();
pila = pila.sig;
}
} // fin class Pila
public class Prueba{
public static void main(String[]args){
//creamos nuestros arrays de enterosint array1[]= {1,2,3,4,5,6,7};
int array2[]= {1,2,3,4
array3[]= {1,2};
int array4[]= {1,2,3,4,5,6,7,8,9,10};
int array5[]= {1};
int array6[]= {1,2,3,4,5};
int array7[]= {1,2,3,4,5,6};
//rellenamos los vectoresVectorEnteros v1=new VectorEnteros();
v1.añadir(array1);
VectorEnteros v2=new VectorEnteros();
v2.añadir(array2);
VectorEnteros v3=new VectorEnteros();
v3.añadir(array3);
VectorEnteros v4=new VectorEnteros();
v4.añadir(array4);
VectorEnteros v5=new VectorEnteros();
v5.añadir(array5);
VectorEnteros v6=new VectorEnteros();
v6.añadir(array6);
VectorEnteros v7=new VectorEnteros();
v7.añadir(array7);
//creamos una pila con los 7 vectores de enteros Pila p1=new Pila(7);
p1.push(v1);
p1.push(v2);
p1.push(v3);
p1.push(v4);
p1.push(v5);
p1.push(v6);
p1.push(v7);
//creamos varias pilas para almacenar en la cola y hacer pruebas con ellas Pila p2=new Pila(7); p2=p1;
Pila p3=new Pila(7);
p3=p1;
Pila p4=new Pila(7);
p4=p1;
Pila p5=new Pila(7);
p5=p1;
Pila p6=new Pila(7);
p6=p1;
Pila p7=new Pila(4);
//cambiamos el orden y el tamañop7.push(v4);
p7.push(v2);p7.push(v3);
p7.push(v1);
Cola c1=new Cola();
c1.encolar(p1);
c1.encolar(p7);
c1.encolar(p3);
c1.encolar(p7);
Cola c2=new Cola();
c2.encolar(p7);
c2.encolar(p6);
c2.encolar(p5);
Cola c3=new Cola();
Cola c4=new Cola();
c4.encolar(p7);
c1.desencolar();
c1.imprimir();
c2.imprimir();
c3.imprimir();
c4.imprimir();
}
}
//Fin clase
//Clase Cola implementada como lista dinámica en la que se almacenan pilas. Observar que se cumple FIFO:
public class Cola{private Nodo primero;
private Nodo ultimo;
public Cola(){primero = null;ultimo = null;}
public boolean vacia(){return (primero == null);}
public void encolar(Pila p)
{Nodo nuevo = new Nodo(p,null);
if(vacia())primero = nuevo;
lseultimo.siguiente = nuevo;
ultimo = nuevo;}
public Pila desencolar(){if(vacia())
{System.err.println(”No hay elementos en la cola\n”);
return null;}
else{Pila p = primero.pila;primero = primero.siguiente;
if(vacia()){ultimo = null;}
return p;
}
}
public void imprimir(){int j=1;
if(!vacia()){
System.out.println(”CONTENIDO DE LA COLA\n”);
while(!vacia())
{System.out.println(”Pila “+j+”: \n”);
Pila p = primero.pila;
primero = primero.siguiente;
ultimo = null;
p.imprimir();
j++;}
System.out.println(”\n”);
}else
{System.out.println(”ESTA COLA ESTÁ VACÍA”);
System.out.println(”\n\n”);}
}
}
//Fin clase
//Clase Pila implementada como array en la que se almacenan vectores de enteros. Observar que se cumple LIFOpublic
class Pila{private int numElementos;private VectorEnteros elementos[];
private int indice;
public Pila(int numElementos)
{this.numElementos=numElementos;indice=-1;
elementos= new VectorEnteros[numElementos];
for(int i=0;
i
i++){elementos[i]=new VectorEnteros();}
}
public int vacia(){return(indice =-1);}
public int llena(){return (indice=numElementos-1);}
public void push(VectorEnteros v){indice++;elementos[indice]=v;}
public VectorEnteros pop(){VectorEnteros v= elementos[indice];
indice–;return v;}
public void imprimir()
{int j=0;
for (int i=elementos.length-1;
i>=0;i–){System.out.print(”Vector “+(j+1)+”\t”);
elementos[i].imprimir();j++;
}System.out.println(”");
}
}
//Fin clase
CLASE VECTOR DE ENTEROS
import java.util.Vector;
import java.util.Enumeration;
public class VectorEnteros {
//vector que va a guardar los enterosprivate Vector vectorenteros;
/*Por simplicidad creamos un array que contenga inicialmente los enteros que queremos guardar.Si queremos modificar el vector, solo hay que modificar el array correspondiente en la
clase Prueba*/private int numeros[];
public VectorEnteros(){
//Creo el vectorvectorenteros=new Vector();}
public void añadir(int n[])
{numeros=n;for (int i=0;
i<>
i++){Integer num=new Integer(numeros[i]);
vectorenteros.addElement(num);}
}
public void imprimir(){Enumeration e=vectorenteros.elements();
while(e.hasMoreElements()){
//Hay que hacer cambio de tipoInteger entero=(Integer)e.nextElement();
System.out.print(entero+” “);
}System.out.println(”");
}
}
//Fin clase