Question
In the enqueue(int x) function of Queue.java, we do not check if the queue is already full. Implement the capacity check feature for enqueue(int x).
In the enqueue(int x) function of Queue.java, we do not check if the queue is already full. Implement the capacity check feature for enqueue(int x). (Hint: Use System.err.println() to print the error message.)
_______________________________________
package ds;
public class Queue {
public int size;
public int[] array;
public int head;
public int tail;
public Queue() {
size = 0;
array = null;
head = 0;
tail = 0;
}
public Queue(int _size) {
size = _size;
array = new int[size];
head = 0;
tail = 0;
}
/*
* Implement the ENQUEUE(Q, x) function
*/
public boolean IsEmpty() {
return (head == 0 && tail == 0);
}
public void enqueue(int x) {
int no;
if (tail == array.length && head == 0)
System.out.println("queue is full");
else {
array[tail] = x;
tail++;
}
}
/*
* Implement the DEQUEUE(Q) function
*/
public int dequeue() {
int num = -1;
if (IsEmpty())
System.out.println("queue is empty");
else {
num = array[head];
head++;
}
return num;
}
/*
* Convert queue to string in the format of #size, head, tail, [#elements]
*/
public String toString() {
String str;
str = size + ", " + head + ", " + tail + ", [";
for (int i = head; i % size < tail; i++)
str += array[i] + ",";
str += "]";
return str;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue q;
q = new Queue(10);
for (int i = 0; i < 5; i++)
q.enqueue(i);
System.out.println(q.toString());
for (int i = 0; i < 2; i++)
q.dequeue();
System.out.println(q.toString());
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started