Can someone fix this code for me so that I dont have to do size + 1 and queue =
ID: 3861306 • Letter: C
Question
Can someone fix this code for me so that I dont have to do size + 1 and queue = new String[6] in the contructors to get the result I want? It works but only when I do this and id like the constructors to stay the same but I cant figure out where I messed up. Whenever it shows a full queue it shows it as empty when using both constructors.
public class MinimalQueue {
String queue[];
int front = -1;
int back = -1;
public MinimalQueue(){
queue = new String[5];
}
public MinimalQueue(int size) {
queue = new String[size];
}
public void enqueue(String element) {
back = (back + 1) % queue.length;
queue[back] = element;
if (front == -1) {
front = 0;
}
}
public String dequeue() {
String element = queue[front];
queue[front] = null;
if (front == back) {
front = back = -1;
} else {
front = (front + 1) % queue.length;
}
return element;
}
public boolean isFull() {
return back == queue.length - 1;
}
public boolean isEmpty() {
return front == -1;
}
public void showQueue() {
for (int i = front; i <= back; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
}
Explanation / Answer
public class MinimalQueue {
String[] queue;
int front;
int back;
int count;
public MinimalQueue() {
queue = new String[5];
}
public MinimalQueue(int size) {
queue = new String[size];
front = -1;
back = -1;
count = 0;
}
public void enqueue(String element) {
if(count < queue.length) //If the queue is not full.
{
back = (back + 1) % queue.length; //Calculates the back index.
queue[back] = element; //Inserts the element at the back.
count++;
}
/* This should not be done. Actually, inserting an element at the back, should not
modify the front index.
if (front == -1) {
front = 0;
}*/
}
public String dequeue() {
String element = "";
if(count != 0)
{
front = (front + 1) % queue.length; //Calculates the front index.
element = queue[front]; //Copies the queue front to element.
queue[front] = null; //Makes the queue front empty.
if (front == back) { //If no elements in queue, re-initialize queue indices.
front = back = -1;
}
count--;
}
return element;
}
public boolean isFull() {
return count == queue.length;
}
public boolean isEmpty() {
return count == 0;
}
public void showQueue() {
for (int i = front+1; i <= back; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
}