54.4k views
0 votes
Write the output produced when the following method is passed each of the following stacks:

public static void mystery1(Stack s) {
Queue q = new LinkedList();
while (!s.isEmpty()) {
int n = s.pop();
q.add(n);
q.add(n); }
while (!q.isEmpty()) {
s.push(q.remove());
}
System.out.println(s);
}

[2, 6, 1] __________________
[42, -3, 4, 15, 9] _____________
[30, 20, 10, 60, 50, 40] _____________

User WhiteHat
by
5.8k points

1 Answer

5 votes

Answer:

The Output for [2, 6, 1] = 1,1,6,6,2,2

The Output for 42,-3,4,15,9 = 9,9,15,15,4,4,-3,-3,42,42

The Output for 30,20,10,60,50,40 = 40,40,50,50,60,60,10,10,20,20,30,30

Step-by-step explanation:

In the following code, we have a while loop which runs until variable s is not empty. Inside the loop, we pop the element from stack and append it to the queue by calling the add function twice so that's all the numbers will be added twice.

Therefore when we print the queue, we get the same number twice as depicted in the following outputs as well.

The Output for [2, 6, 1] = 1,1,6,6,2,2

The Output for 42,-3,4,15,9 = 9,9,15,15,4,4,-3,-3,42,42

The Output for 30,20,10,60,50,40 = 40,40,50,50,60,60,10,10,20,20,30,30

User Erlkoenig
by
5.3k points