In: Computer Science
write JAVA code with the following condition
Write the pseudocode for a new data type MyStack that implements a stack using the fact that you have access to a queue data structure with operations enqueue(), dequeue(), isEmpty(). Remember that every stack should have the operations push() and pop().
Hint: use two queues, one of which is the main one and one is temporary. Please note that you won’t be able to implement both push() and pop() in constant time. One of the two will have to run in O(n), where n is the number of elements in the stack.
//Source Code:
// MyStack.java
import java.util.LinkedList; import java.util.Queue; class MyQueue<E>{ Queue<E> q = new LinkedList<>(); public void enqueue(E a){ q.add(a); } public E dequeue(){ return q.poll(); } public boolean isEmpty(){ return q.isEmpty(); } } public class MyStack<E> { private MyQueue<E> mainQueue = new MyQueue<>(); // This will take O(1) time public void push(E x){ mainQueue.enqueue(x); System.out.println("Pushed " + x + " into the Stack."); } // This will take O(n) time public void pop(){ MyQueue<E> tempQueue = new MyQueue<>(); E a = null; while (!mainQueue.isEmpty()){ a = mainQueue.dequeue(); if (mainQueue.isEmpty()){ break; } tempQueue.enqueue(a); } mainQueue = tempQueue; if (a == null){ System.out.println("Stack is Empty!! Underflow."); }else { System.out.println("Poped out " + a + " from the Stack."); } } public static void main(String[] args) { MyStack<Integer> myStack = new MyStack<>(); myStack.push(10); myStack.push(20); myStack.push(30); myStack.pop(); myStack.pop(); myStack.pop(); myStack.pop(); } }
// Screenshot:
// Output:
// If you have any query do ask in the comments section.
// If you found the answer helpful do give a Thumbs Up!!