Stack/Queue Behavior (16 points)
Stack Methods:
- s.pop(): Removes the top element and returns this element as a value
- s.push(n): Pushes the value of n onto the stack
Queue Methods:
- q.size(): Returns the size of the queue
- q.add(n): Adds n to the queue
- q.remove(): Removes the first element and returns this element as a value
Suppose at the beginning of the mystery function, the stack s has the values [2, 4, 6, 8] where 2 is the top (i.e. s.pop() will return 2 for the first call). What is the contents of s after mystery runs?
public static void mystery(Stack<int> s) {
Queue<int> q = new Queue<int>();
while (!s.isEmpty()) {
q.add(s.pop());
}
int size = q.size();
for (int i = 0; i < size; i++) {
int n = q.remove();
q.add(n);
s.push(n);
}
while (!q.isEmpty()) {
s.push(q.remove());
}
}