Java stack intercalating values

Asked

Viewed 441 times

2

have two stacks have to create the third interleaving the values of the two stacks created the stack and all I’m having a lock to implement the code to interlink

follows 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);
  • I’m sorry, I didn’t quite understand what you meant by "block," could you explain to me?

  • Hello, @user3652472! Your question has been closed by the community because with the data provided it is not possible to give a clear and objective answer. We don’t exactly understand the problem. However, you can edit your question by adding logs, error messages, application code, and something that makes it possible for someone to answer it. Also feel free to create new questions or even answer, but I suggest reading about how to ask a good question in our Help Center. Thank you!

1 answer

2


Use a control variable to determine which stack you should take 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 batteries has an element. Also implement a method to find out when the stack is empty, it will help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.