Stack of batteries in java

2

I have several final projects in the subject Data Structure. In all I'm doing well, but in this specific, for more than I try, I can not find the solution.

The problem proposes the following:

  

Stack of pilitas: The elements of ED PILITA are of any type of data, the elements of the ED PILA are of type PILA.

So far, I have taken these methods from the class PILITA

  public class pilita{
    Object vectorPila[];
    int tope;
    public pilita(int tam){
        vectorPila=new Object[tam];
        tope=-1;
    }
    public void inicializarPila(){
        tope=-1;
    }
    public void push(Object dato){
        tope++;
        vectorPila[tope]=dato;
    }
    public Object pop(){
        Object fuera=vectorPila[tope];
        tope--;
        return fuera;
    }
    public boolean pilaVacia(){
        return tope==-1;
    }
    public boolean pilaLlena(){
        return vectorPila.length-1==tope;
    }
    public Object cima(){
        return vectorPila[tope];
    }
    public Object contar(){
        return tope+1;
    }
}

But the problem is that I do not know how the combination of PILA with PILITA could be implemented. If you could help me find a solution, I would greatly appreciate it.

    
asked by Alan Erick Salgado Vazquez 26.10.2016 в 03:33
source

1 answer

3

First, I would take advantage of using generics in your class Pilita to support any type and you can check the type at compile time, thus avoiding problems of manual casting in your code. A base example about your class:

public class Pilita<T> {
    Object vectorPila[];
    int tope;

    public void push(T dato){
        tope++;
        vectorPila[tope] = dato;
    }

    public T pop() {
        Object fuera = vectorPila[tope];
        tope--;
        return (T)fuera;
    }

    //demás métodos, constructores, etc
}

Since the class Pilita already stores a stack, what your class Pila can contain is a Pilita of Pilita s:

public class Pila {
    private Pilita<Pilita<?>> pilaDePilas;
    int tam;

    public Pila(int tam) {
        this.tam = tam;
        pilaDePilas = new Pilita<>(tam);
    }

    //resto de métodos...
}
    
answered by 26.10.2016 в 05:18