In C, how do you remove only odd numbers from a stack? I was thinking of removing item from item and passing to a vector, however the stack size is not given.
In C, how do you remove only odd numbers from a stack? I was thinking of removing item from item and passing to a vector, however the stack size is not given.
You have a stack of numbers that we'll call A.
The goal is to get all the odd numbers of this stack. Since it is a stack, there is no way to go through the elements without necessarily destroying them (otherwise it would not be a stack).
So what you do is more or less what is 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;
In this way, you move the elements from A to B and filter the odd ones. In stack B they will be in the reverse order. When you finish you do the opposite move, and they will get the correct order on stack A, which was also the original stack. The result is that stack A will have the odd elements removed.