Stack in Java interleaving values [closed]

2

I have two stacks I have to create the third one interleaving the values of the two stacks I created the stack and all I'm having a lock to implement is the code to interleave

follow the code:

public class Pilha {
    private Stack p;

    public Pilha()
    {
       p = new Stack();
    }

    public void insere(int x)
    {
        p.push(x);
    }

    public int remove()
    {
        return (int) p.pop();
        }
}

public static void main(String[] args) {
    // TODO code application logic here

    int a=2, b=3, c=4, d=5,e=6,f=7,g=8,h=9;
    Pilha p1 = new Pilha();
    Pilha p2 = new Pilha();
    Pilha p3 = new Pilha();
    p1.insere(a);
    p1.insere(b);
    p1.insere(c);
    p1.insere(d);
    p2.insere(e);
    p2.insere(f);
    p2.insere(g);
    p2.insere(h);
    
asked by anonymous 12.09.2014 / 22:53

1 answer

2

Use a control variable to determine which stack you want to remove the element from. Something like:

int pilha = 1;
if (pilha == 1) {
    p3.insere(p1.remove());
    pilha = 2;
}
else {
    p3.insere(p2.remove());
    pilha = 1;
}

Try to use this idea with a loop while one of the cells has an element. Also implement a method to find out when the stack is empty, it will help.

    
12.09.2014 / 23:28