Fill in the method stub below so that it removes all elements from q and returns
ID: 3793430 • Letter: F
Question
Fill in the method stub below so that it removes all elements from q and returns a stack containing, from top to bottom, the elements given in q from front to back, followed by the elements given in q from back to front. For example, if q initially contains, from front to back, the sequence <1, 2, 3, 4>, then the stack returned should contain the sequence, from top to bottom, <1, 2, 3, 4, 4, 3, 2, 1>, and q should end up being empty. You may use any additional data structures that you feel are appropriate. You may assume that q is not null. You may not add any code outside of this method.
private Stack<int> MoveToStack(Queue<int> q)
Explanation / Answer
Solution:
PFA the complete implementation of the method asked, which will be returning a Stack<Integer>.
The explanation for the logic is present as comments in between the code. Java is used to implement the above (as there was no language specification) and a main() is provided with a set of sample input for testing purpose.
Conversion.java
package new_Cheg_6;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Conversion {
private static Stack<Integer> moveToStack(Queue<Integer> q){
Stack<Integer> stackToReturn = new Stack<Integer>();
Integer[] bufferArray1 = new Integer[q.size()];
int counter=0;
//Removing elements from the queue by using poll()
//which removes the head currently being pointed
while(!q.isEmpty()){
bufferArray1[counter]= q.poll();
counter++;
}
//Appending elements to the stack as per requirement
for(int i = 0; i<bufferArray1.length; i++){
stackToReturn.add(bufferArray1[i]);
}
for(int i = bufferArray1.length; i>0; i--){
stackToReturn.add(bufferArray1[i-1]);
}
return stackToReturn;
}
public static void main(String[] args) {
//In Java Queue is an interface and can be
//instantiated by using an implementing class only
//which in this case is LinkedList class.
Queue<Integer> q = new LinkedList<Integer>();
q.offer(3);q.offer(9);q.offer(12);q.offer(0);q.offer(15);
System.out.println("Queue before conversion[front->back]:");
q.forEach(queueElement -> System.out.print("->"+queueElement));
System.out.println();
//Call to the method
Stack<Integer> returnedStack = moveToStack(q);
System.out.println("Converted stack[top -> bottom]:");
returnedStack.forEach(stackElement -> System.out.print("->"+stackElement));
System.out.println();
System.out.println("Queue after conversion[front->back]:"+q);
}
}
Output:
Queue before conversion[front->back]:
->3->9->12->0->15
Converted stack[top -> bottom]:
->3->9->12->0->15->15->0->12->9->3
Queue after conversion[front->back]:[]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.