CSE 143 Section Handout #12
3.
Stack and Queue Programming
.
Write a method
removeMin
that accepts a stack of integers as a
parameter and removes and returns the smallest value from the stack.
For example, if a variable
s
stores:
bottom [2, 8, 3, 19, 7, 3, 2, 42, 9, 3, 2, 7, 12, -8, 4] top
And we make the following call:
int n = removeMin(s);
The method removes and returns
-8
, so
n
will store -8 after the call and
s
will store the following values:
bottom [2, 8, 3, 19, 7, 3, 2, 42, 9, 3, 2, 7, 12, 4] top
If the minimum value appears more than once, all occurrences of it should be removed.
For example, given
the stack above, if we again call
removeMin(s);
, it would return
2
and would leave the stack as follows:
bottom [8, 3, 19, 7, 3, 42, 9, 3, 7, 12, 4] top
You may use one queue as auxiliary storage.
You may not use any other structures to solve this problem,
although you can have as many primitive variables as you like.
You may not solve the problem recursively.
You may assume that the stack is not empty.
For full credit, your solution must run in O(
n
) time.
You have access to the following two methods and may call them as needed to help you solve the problem:
public static void
s2q
(Stack<Integer> s, Queue<Integer> q) {
while (!s.isEmpty()) {
q.add(s.pop());
// Transfers the entire contents
}
// of stack s to queue q
}
public static void