Question

JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public int size() public void insert(String value) public String remove() private void shiftStacks() public boolean isEmpty() public boolean isFull()

public class MyQueue{
private int maxCapacity = 4;
private Stack<String> stack1;
   private Stack<String> stack2;
  
public MyQueue(){
}
public int size(){
}
public void insert(String value){
}
public String remove(){
}
private void shiftStacks(){
}
public boolean isEmpty() {
}
public boolean isFull(){
}
  
@Override //[QueueSize:Full/Empty:QueueElementsList]
   public String toString(){
       shiftStacks();
       StringBuilder sb = new StringBuilder("[");
       sb.append(this.size()).append(":");
       if(this.isEmpty())
           sb.append("Empty").append(":");
       else if (this.isFull())
           sb.append("Full").append(":");
       while(!isEmpty()){
           sb.append(this.remove());
           if(this.size()!=0) sb.append(", ");
       }
       sb.append("]");
       return sb.toString();
   }   
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
MyQueue.java:

import java.util.Stack;

public class MyQueue{
    private int maxCapacity = 4;
    private Stack<String> stack1;
    private Stack<String> stack2;

    public MyQueue(){
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public int size(){
        return stack1.size() + stack2.size();
    }

    public void insert(String value){
        if(value == null || value == "" || value == " ")
            return;
        if(stack1.size() == maxCapacity)
            System.out.println("Reached maximum capacity");
        stack1.push(value);
    }

    public String remove(){
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        String popped = stack2.pop();
        if(stack1.isEmpty()){
            while(!stack2.isEmpty()){
                stack1.push(stack2.pop());
            }
        }
        return popped;
    }

    private void shiftStacks(){
//        Stack<String> temp = stack1;
//        stack1 = stack2;
//        stack2 = temp;
    }

    public boolean isEmpty() {
        return stack1.isEmpty();
    }

    public boolean isFull(){
        if(stack1.size() == maxCapacity){
            return true;
        }
        return false;
    }

    @Override //[QueueSize:Full/Empty:QueueElementsList]
    public String toString(){
        shiftStacks();
        StringBuilder sb = new StringBuilder("[");
        sb.append(this.size()).append(":");
        if(this.isEmpty())
            sb.append("Empty").append(":");
        else if (this.isFull())
            sb.append("Full").append(":");
        while(!isEmpty()){
            sb.append(this.remove());
            if(this.size()!=0) sb.append(", ");
        }
        sb.append("]");
        return sb.toString();
    }
}
Add a comment
Know the answer?
Add Answer to:
JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The class pictured below is designed to implement an integer queue using two stacks. Assume the...

    The class pictured below is designed to implement an integer queue using two stacks. Assume the stack methods all work as desired (though their implementations are not shown). .(a) Trace what happens in the following situation, showing intermediate steps (values of variables, what is in the stacks, and what is in the queue at various points in the methods, not just the results of the methods). • Start with an empty queue. Enqueue 5, then 16, then 7. Dequeue twice....

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • Design and implement a class Q that uses Q.java as a code base. The queue ADT...

    Design and implement a class Q that uses Q.java as a code base. The queue ADT must use class LinkedList from Oracle's Java class library and its underlying data structure (i.e. every Q object has-a (contains) class LinkedList object. class Q is not allowed to extend class LinkedList. The methods that are to be implemented are documented in Q.java. Method comment blocks are used to document the functionality of the class Q instance methods. The output of your program must...

  • Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks...

    Recursively sorting an unbounded stack (java) in ascending order? (This assignment is only limited to stacks only, No other data structures are allowed) My professor gave us a hint on how to implement this, however she wants the comparable interface to be used. im not sure on how to do this. Hint: May want to use a public method that accepts the original stack and then creates the two additional stacks needed. This method then calls a private method that...

  • In C++ Implement a queue data structure using two stacks. Remember a queue has enqueue and...

    In C++ Implement a queue data structure using two stacks. Remember a queue has enqueue and dequeue functions. You could use either the array or linked list implementation for stacks and queues. Source for stack array: --------------------------------------------------- #include<iostream> #define SIZE 100 #define NO_ELEMENT -999999 using namespace std; class Stack { int arr[SIZE]; // array to store Stack elements int top; public: Stack() { top = -1; } void push(int); // push an element into Stack int pop(); // pop the...

  • C++ Please ensure code is fully working, will rate Question to be answered:    Repeat Exercise...

    C++ Please ensure code is fully working, will rate Question to be answered:    Repeat Exercise 1 for the class linkedStackType question one:        Two stacks of the same type are the same if they have the same number of elements and their elements at the corresponding positions are the same. Overload the relational operator == for the class stackType that returns true if two stacks of the same type are the same, false otherwise. Also, write the definition...

  • Create a program named NonZeroNumQueue.java then copy the contents from NonZeroNumQueue.txt. Then implement enqueue method. To...

    Create a program named NonZeroNumQueue.java then copy the contents from NonZeroNumQueue.txt. Then implement enqueue method. To get credit, DO NOT add or alter any data members/methods except the enqueue(int num). The NonZeroNumQueue will NOT accept zero, which mean you can enqueue any whole numbers EXCEPT 0(zero). You have already noticed that the queue is NEVER full, so the isFull() always returns false. given NonZeroNumQueue.txt public class NonZeroNumQueue{ private int[] data; private int total; private int front; private int tail; public...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT