Interfaz a utilizar
package Pila;
/**
* @author Daniel Cataño Restrepo
*/
public interface IPila<E>{
public boolean isEmpty();
public E peek();
public E pop();
public void print();
public void push(E target);
}
La clase Pila
package Pila;
/**
* @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
*/
public class Pila<E> implements IPila<E>{
E[] data;
public Pila(){
data=(E[])new Object[0];
}
public boolean isEmpty() {
return data.length==0;
}
public E peek() {
return data[0];
}
/**
* Remueve el primer elemento de la pila, y lo retorna
*/
public E pop() {
E firstElement=data[0];
E[] temp=(E[])new Object[data.length-1];
for(int i=0; i<data.length-1; i++)
temp[i]=data[i+1];
data=temp;
return firstElement;
}
public void print() {
System.out.print("[");
for(int i=0; i<data.length; i++){
if(i==data.length-1)
System.out.print(data[i]);
else
System.out.print(data[i]+", ");
}
System.out.println("]");
}
/**
* Agrega un nuevo elemento a la pila
*/
public void push(E target) {
E[] temp=(E[])new Object[data.length+1];
for(int i=data.length-1; i>=0; i--){
temp[i+1]=data[i];
}
temp[0]=target;
data=temp;
}
}
La clase Principal
package Pila;
/**
* @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
*/
public class Main {
public static void main(String[] args) {
Pila p=new Pila();
p.push(1);
p.push(2);
p.push(3);
p.push(4);
p.push(1);
p.push(2);
p.push(3);
p.push(4);
p.print();
p.pop();
p.pop();
p.pop();
p.pop();
p.print();
}
}
No hay comentarios:
Publicar un comentario