Remove odd numbers from a stack

Asked

Viewed 1,494 times

2

In C how is it done to remove only odd numbers from a stack? I was thinking of removing item by item and moving to an array, but the stack size is not given.

  • 1

    Include what you have already tried to do, how you have implemented your stack data structure, etc., in this way makes your doubt clearer, making it easier to help you.

  • What code are you using, could post a part for us to see?

  • If the size is not given, then you need either a chained list or some other data structure that grows as needed. Assuming this is an exercise, I think the best is a chained list. You’re familiar with this concept?

1 answer

1


You have a stack of numbers that we’ll call A.

The goal is to get all the odd numbers out of this stack. Since it is a pile, there is no way to go through the elements without necessarily destroying them (otherwise it would not be a pile).

So what you do is more or less what’s in the following algorithm:

B = nova pilha;

while (A não está vazia) {
    int t = remove elemento do topo de A;
    if (t % 2 == 0) {
        empilha t em B;
    }
}

while (B não está vazia) {
    int t = remove elemento do topo de B;
    empilha t em A;
}

apaga B;

This way, you move the elements from A to B and filter the odd ones. On the B stack they will be in reverse order. When finished you make the opposite move, and they will be the correct order on stack A, which was also the original stack. The result is that stack A will have the odd elements removed.

Browser other questions tagged

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