Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The pseudocode below would reverse the contents of the stack s1. (assume the sta

ID: 3718288 • Letter: T

Question

The pseudocode below would reverse the contents of the stack s1. (assume the stack & queue store ints).

Stack s1 = new Stack();   // assume s1 is populated with data somehow Queue q1 = new Queue();

while ( ! s1.isEmpty() ) { // move stack contents to q1      int item = s1.pop();      q1.enqueue( item );

}

while ( ! q1.isEmpty() ) { // move queue contents to s1 int item = q1.dequeue(); s1.push( item )

}

Assume stack s1 and queue q1 have been populated with data.

Write client pseudocode (using any combination of extra stacks & queues ) to solve the following:

1.Reverse the stack s1

2.Remove all even numbers from the stack s1

3. Nondestructively make a copy of q1. Name the copy q2.   (Nondestructively means that q1 is the same before and after the copy is made).

  

Explanation / Answer

Q. Reverse the stack s1

Queue q1 = new Queue();

while ( ! s1.isEmpty() ) { // move stack contents to q1   

int item = s1.pop();   

q1.enqueue( item );

}

while ( ! q1.isEmpty() ) { // move queue contents to s1  

int item = q1.dequeue();  

s1.push( item )

}

2.Remove all even numbers from the stack s1

Stack s2 = new Stack();

while ( ! s1.isEmpty() ) { // move stack contents to s2   

int item = s1.pop();  

if(item%2 == 1)   

s2.push(item );

}

while ( ! s2.isEmpty() ) { // move stack2 contents to s1  

int item = s2.pop();  

s1.push( item )

}

Q. Nondestructively make a copy of q1. Name the copy q2. (Nondestructively means that q1 is the same before and after the copy is made).

Queue q2 = new Queue();

Queue temp = new Queue();

while ( ! q1.isEmpty() ) { // move q1 contents to q2 and temp   

int item = q1.enqueue();   

q2.enqueue( item );

temp.enqueue( item );

}

// preserving q1

while ( ! temp.isEmpty() ) { // move temp queue contents to q1  

int item = temp.dequeue();  

q1.enqueue( item )

}