Consider a stack \( S \) of integers. Write a function \(\texttt{PositiveStack(...)}\) that takes as input a stack \( S \) and removes all negative integers in \( S \). The order of the other integers in the stack is preserved. You may use the stack operations in your answer.
Example:
\(\begin{array}{p{1cm} p{1cm} p{1cm}}
\begin{array}{|c|}
4 \\
8 \\
-7 \\
0\\
-1 \\
3 \\
3\\
-2 \\
1 \\
\hline
\end{array}
& becomes &
\begin{array}{|c|}
\\
\\
\\
4 \\
8 \\
0\\
3 \\
3\\
1 \\
\hline
\end{array}
\end{array}\)
Difficulty level
Video recording
This exercise is mostly suitable for students
void PositiveStack(stack *s)
{
element e;
stack q=CreateStack();
while(Top(*s,&e))
{
Pop(s);
if(e>=0)
Push(&q,e);
}
while(Top(q,&e))
{
Pop(&q);
Push(s,e);
}
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Star pattern 20