Question: Define a StackByQueue class. In this class, you need to implement a stack by using two queues you designed previously. You need to design and

Define a StackByQueue class. In this class, you need to implement a stack by using two queues you designed previously. You need to design and implement this class by yourself. The StackByQueue class need the following public methods:

public class StackByQueue

Methods:

public void push(String x); // push a string into stack

public String pop(); // pop out a string from the stack

public String top(); // return the top element in the stack

public boolean isEmpty(); // return whether this stack is empty

The queues designed before based on Array:

public class MyQueue {

private int front, rear, size; // the index for firs, the index for last array and current size of your queue

private String[] queueArray; // an array to save all elements in your queue

private int maxSize; // the maximum size of your queue

public MyQueue(int maxSize) { this.maxSize = maxSize; queueArray = new String[maxSize]; front = rear = 0; //Indicate this queue is empty }

//To get the current size of this queue

public int getSize(){ if (isEmpty())

{ return 0; }else { return (maxSize + rear - front)%maxSize; } }

//Add a new element from the rear

public void enqueue(String s) { if (getSize() == maxSize - 1) { return ; }else { queueArray[rear] = s; rear = (rear+1)%maxSize; } }

//Remove a element from the front

public String dequeue(){ if (isEmpty()){ return null; }else { return queueArray[front++]; } }

//To test if there are some elements in this queue

public boolean isEmpty(){ return (front == rear); }

//To Test if the amount of elements reach the maxsize of this queue

public boolean isFull(){ return (rear == maxSize-1); }

//To get the first element for this queue

public String frontElement(){ if (isEmpty()){ return null; }else { return queueArray[front]; } } }

!!!!Please do not use LinkedList to implement!!!!!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!