Question

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. Enqueue 3. Dequeue once. .(b) Much of the code is uncommented. Add comments to explain the key steps in these methods.

.(c) Explain in your own words/images why this dequeue() method works.

(d) What situations are not considered in the methods written here that should be?

Screen Shot 2020-10-02 at 1... Open with Preview class myQueue { //implementing a queue using two stacks private MyStack stac

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • Part a:
    1. Enqueue 5 :
    It will push element in stack1. Now stack1 will have [ 5 ] and top of stack will point to 5
    2. Enqueue 16 : It will push element in stack1. Now stack1 will have [ 5, 17] and top of stack will point to 17
    3. Enqueue 7 : It will push element in stack1. Now stack1 will have [ 5, 17, 7 ] and top of stack will point to 7.
    4. Dequeue : As stack2 is empty so dequeue function will pop out all the elements of stack1 and will push them in stack2. Now stack2 will have [ 7, 17, 5 ] and top of stack will point to 5 and stack1 will be empty.After pushing all the elemts in stack2 the function will return stack.pop () means the element that top pointer points to i.e. 5 in this case and now stack2 will have [ 7, 17 ] and top of stack will point to 17.
    5. Dequeue : As stack2 is not empty so function will return stack.pop () means the element that top pointer points to i.e. 17 in this case and now stack2 will have [ 7 ] and top of stack will point to 7.
    6. Enqueue 3 :It will pust element in stack1. Now stack1 will have [ 3 ] and top of stack will point to 3.

    After all of the above operations :
    stack1 will have [ 3 ] and top of stack will point to 3 and stack2 will have [ 7 ] and top of stack will point to 7.

    Part b:
    class myQueue {
    private MyStack stack1;
    private MyStack stack2;

    public MyQueue(int max) { // Constructor that will initialize both stack with size as max
    stack1=new MyStack(max);
    stack2=new MyStack(max);
    }

    public void enqueue (int val) { // Whenever we want to perform enqueue operation in queue it will puch that element in stack1
    stack1.push(val);
    }

    public int dequeue ( ) {
    if (stack2.isEmpty() ) { // If stack2 is empty then it will push all the elements of stack1 in stack2 so that element comes in the order in which they should be pop out from queue ( i.e. reverse of stack order i.e. reverse of LIFO i.e. in FIFO order) But if the stack2 was not empty then it will directly pop out top element of stack2 without pushing element of stack 1 into stack2.
    while (! stack1.isEmpty() ) { // pushing elements of stack1 into stack2
    int moveval=stack1.pop();
    stack2.push(moveval);
    }
    }
    return stack2.pop (); //it will return the top element of stack2 i.e. first element of queue.
    }
    }

    Part c :
    This method will work because when the stack2 is empty then we are pushing all elements of stack1 into stack2. This means the element in stack2 will come in reverse order of elements that they were in stack1.(i.e. reverse of LIFO as elements in stack1 were in LIFO order so reverse of LIFO is FIFO this is what we wants in queue). Now whenever the dequeue operation will be there then we will pop out element from stack2. But when stack2 agains become empty then we will again push all the elements of stack1 into stack2 and will perform the same procedure.
    So, by doing so we are popping out element from stack2 as we do from queue.

    Part d:   
    If we will perform dequeue operation without performing any enqueue operation then in that case above code will give ur some error.

    public int dequeue ( ) {
    if (stack2.isEmpty() ) { //As stack2 is empty so it will go in while loop
    while (! stack1.isEmpty() ) { //As stack1 is also empty so it will come out of while loop
    int moveval=stack1.pop();
    stack2.push(moveval);
    }
    }
    return stack2.pop (); //As stack2 is empty but it is performing stack2.pop() so it will give us error.
    }
    }

    So in order to handle it before doing stack2.pop() we can check whether stack2 is empty or not and then can perform operation accordingly.

Add a comment
Know the answer?
Add Answer to:
The class pictured below is designed to implement an integer queue using two stacks. Assume the...
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
  • 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...

  • 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...

  • JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test...

    JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test it is not executing but my stack is working fine, can you fix it please! MyQueue.java Implement a queue using the MyStack.java implementation as your data structure.  In other words, your instance variable to hold the queue items will be a MyStack class. enqueue(String item): inserts item into the queue dequeue(): returns and deletes the first element in the queue isEmpty(): returns true or false...

  • 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: ");...

  • 2. Consider a circular array based Queue as we have discussed in the lectures (class definition...

    2. Consider a circular array based Queue as we have discussed in the lectures (class definition given below for reference) public class CircArrayQueue<E> implements Queue<E private EI Q private int front-0 indicates front of queue l indicates position after end of queue private int end-0: public CircArrayQueue( public int getSize (.. public boolean isEmpty ( public void enqueue (E e)... public E dequeue ) throws EmptyQueueException... Il constructor We are interested in implementing a Stack class based on the above...

  • e. public class Queue { // Uses the correct Stack class from ME2 Ex 19 private Stack mStack; public Queue() { setStack(new Stack()); } public Queue enqueue(E pData) { getStack().push(pData); return t...

    e. public class Queue { // Uses the correct Stack class from ME2 Ex 19 private Stack mStack; public Queue() { setStack(new Stack()); } public Queue enqueue(E pData) { getStack().push(pData); return this; } public E dequeue() { return getStack().pop(); } public E peek() { return getStack.peek(); } private Stack getStack() { return mStack; } private void setStack(Stack pStack) { mStack = pStack; } } f. public class Queue extends Stack { // Uses the correct Stack class from ME2 Ex...

  • HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #include<iostream> #define SIZE...

    HI USING C++ CAN YOU PLEASE PROGRAM THIS ASSIGNMENT AND ADD COMMENTS: stackARRAY: #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 top element from Stack int topElement(); // get the top element void display(); // display Stack elements from top to bottom }; void Stack...

  • i was able to make sense on the others but this two i need help Name:...

    i was able to make sense on the others but this two i need help Name: ImprovedQueue<T> Access Modifier: public Implements: QueueInterface<T> Instance variables Name: front Access modifier: private Data type: QueueNode<T> Constructors: Name: ImprovedQueue Access modifier: public Parameters: none (default constructor) Task: sets the value of front to null Methods Name: isEmpty Access modifier: public Parameters: none Return type: boolean Task: returns true if the front is equal to null; otherwise return false Name: dequeue                            Access modifier: public Parameters:...

  • 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...

  • 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            {               ...

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