First, you need to remember that a stack has the English LIFO behavior last input, first output; i.e. the last one in will be the first one out. So, when you pop elements of P and stack them into Q, the order in Q will be reversed, so you need to reverse the order of Q by turning the elements to P.
The algorithm is basically this:
- As long as P is not empty:
- Pops an element of P;
- If element equals X, go back to step 1;
- Stack element in Q;
- While Q is not empty:
- Pops an element of Q;
- Stack element in P;
That is to say:
P: Pilha<elementos de P>
Q: Pilha<vazia>
Enquanto P não estiver vazia faça:
Elemento = P.desempilha()
Se Elemento é diferente de X:
Q.empilha(Elemento)
Enquanto Q não estiver vazia faça:
Elemento = Q.desempilha()
P.empilha(Elemento)
At the end, stack P will be the original stack, in the same order, without elements equal to X.
If it’s in Python, a lot can be simplified during code implementation.
Hello, put the code in the question for users to analyze
– renanvm