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

A Stack class (public class Stack<T>) has as its only public methods public void

ID: 3838425 • Letter: A

Question

A Stack class (public class Stack<T>) has as its only public methods public void push(T t) and public T pop(). pop() throws a stackException(provided else where) if it is called with an empty stack. A queue class (public class Queue<T>) has as its only public methods public void enqueue(T t) and public T dequeue(). dequeue() throws a QueueException(provided elsewhere) if it is called with an empty queue. A program creates an instace of each class:

Stack<Integer> s = new Stack<Integer>();

Queue<Integer> q = new Queue<Integer>();

Assume that s is empty and that q is not. Write code which using s, will leave q with its elemetns reveresed in their order.

Explanation / Answer

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class queueStack{
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
Queue<Integer> queueReverse = new LinkedList<Integer>();


public void initializeQueue(int data){
   queue.add(data);
   }


public void addintoStack(){
   for(int s : queue) {
       stack.add(s);
   }
}

public Queue<Integer> addintoReverseQueue(){
while (stack.size()>0) {
   queueReverse.add(stack.pop());
}
return queueReverse;

}
}

//////////////main program to call the functionality

import java.util.LinkedList;
import java.util.Queue;

public class QueueStackApp {
public static void main(String[] args) {

   queueStack queueUsingStack = new queueStack();
   Queue<Integer> queueReverse = new LinkedList<Integer>();
     
   System.out.println("Adding elements into Queue");
   queueUsingStack.initializeQueue(10);
   queueUsingStack.initializeQueue(20);
   queueUsingStack.initializeQueue(30);
   queueUsingStack.initializeQueue(40);
   queueUsingStack.initializeQueue(50);
   queueUsingStack.initializeQueue(60);
     
   // this will put the elements into stack
   queueUsingStack.addintoStack();
     
   // this will pop the elements from stack and put it into queue. the new queue will be rever of original queue
   queueReverse = queueUsingStack.addintoReverseQueue();
   System.out.println("reverse queue elements are");
   for(int s : queueReverse) {
       System.out.println(s);
       }

}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote