lunes, 12 de febrero de 2018

Otro ejemplo de pilas

En el blog de aprende Java encontramos el siguiente ejemplo sobre pilas

https://curiotecnology.blogspot.mx/2012/10/pilas-java.html


código de la pila en java

Clase principal


public class Principal {
public static void main(String args[])
{
                /*SE CREA Y SE INSTANCIA EL OBJETO DEL TIPO DE LA CLASE: Pilando*/
Pilando objPilando = new Pilando();
                /*SE LLAMAN A LOS MÉTODOS DE LA CLASE: Pilando*/
objPilando.ingresar();

objPilando.show1();
objPilando.show2();
objPilando.show3();

objPilando.sacar();
}
}


clase pilando



import java.util.*;
public class Pilando {

        /*CREANDO LA PILA*/
Stack pila = new Stack();

/*INGRESANDO ELEMENTOS A LA PILA  En este caso se agregaran los numeros 1, 2 y 3*/
public void ingresar()
{
      for (int x=1;x<=3;x++)
      {
      pila.push(Integer.toString(x));
      }
}

        /*VACIA LA PILA, EN CASO DE ENCONTRARSE VACIA, MUESTRA EL MENSAJE "La pila esta vacía!!!"*/
public void sacar()
{
      while (this.empty() == 1)
      {
      System.out.println("Sacando el elemento "+pila.pop());
      }
      System.out.println("La pila esta vacía!!!");
}

/*
* MUESTRA EL PRIMER ELEMENTO QUE FUE AGREGADO A LA PILA
* */
public void show1()
{
System.out.println("El primer elemento agregado es ---> "+pila.firstElement().toString());
}

/*
* MUESTRA EL ULTIMO ELEMENTO QUE FUE AGREGADO A LA PILA
* */
public void show2()
{
/*
* MUESTRA EL ULTIMO ELEMENTO QUE FUE AGREGADO A LA PILA
* */
System.out.println("El ultimo elemento agregado es ---> "+pila.lastElement().toString());
}

/*
* MUESTRA EL TAMAÑO DE LA PILA -LA CANTIDAD DE ELEMENTOS DE LA PILA-
* */
public void show3()
{
System.out.println("La cantidad de elementos es de ---> "+pila.size());
}

/*
*  DE VUELVE 0 SI LA PILA ESTA VACIA
* */
public int empty()
{
int valid = 1;
if(!pila.empty())
{
valid = 1;
}
else
if(pila.empty())
{
valid = 0;
}
return valid;
}
}


martes, 6 de febrero de 2018