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

I need an output with this code. Can anyone Finish this code? Please add Test cl

ID: 3793427 • Letter: I

Question

I need an output with this code.

Can anyone Finish this code?

Please add Test client to check

--------------------------------------

import java.util.ArrayDeque;

import java.util.Deque;

class MyQueue {

  

  

Deque newStack = new ArrayDeque<>();

Deque oldStack = new ArrayDeque<>();

public void push(int x) {

newStack.push(x);

}

public void pop() {

if(oldStack.isEmpty()) moveToOld();

oldStack.pop();

}

public int peek() {

if(oldStack.isEmpty()) moveToOld();

return oldStack.peek();

}

public boolean empty() {

return newStack.isEmpty() && oldStack.isEmpty();

}

private void moveToOld() {

while(!newStack.isEmpty()) oldStack.push(newStack.pop());

}

}

Queue with two stacks. Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.

Explanation / Answer

MyQueue.java

import java.util.NoSuchElementException;
import java.util.Stack;

class MyQueue {

   Stack<Integer> newStack = new Stack<Integer>();
   Stack<Integer> oldStack = new Stack<Integer>();
  
   public void push(int x) {
       newStack.push(x);  
   }
  
   public void pop() {  
      
       if(empty())
           throw new NoSuchElementException("Queue is empty!!");
      
       if(oldStack.isEmpty()) moveToOld();
      
       oldStack.pop();      
   }
  
   public int peek() {  
      
       if(empty())
           throw new NoSuchElementException("Queue is empty!!");
      
       if(oldStack.isEmpty()) moveToOld();
      
       return oldStack.peek();
      
   }
  
   public boolean empty() {
  
       return newStack.isEmpty() && oldStack.isEmpty();
  
   }
  
   private void moveToOld() {
  
       while(!newStack.isEmpty()) oldStack.push(newStack.pop());
  
   }

}


Test.java

public class Test {
  
   public static void main(String args[]){
       MyQueue queue = new MyQueue();
      
       queue.push(1);
       queue.push(2);
       queue.push(3);
       queue.push(4);
      
       System.out.println(queue.peek());
       queue.pop();
       System.out.println(queue.peek());
       queue.push(5);
       System.out.println(queue.peek());
       queue.pop();
       queue.pop();
       queue.pop();
       queue.push(6);
       System.out.println(queue.peek());
       queue.pop();
       queue.pop();
       System.out.println(queue.peek());
      
   }

}

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