Question: In the dequeue() function of Queue.java, we do not check if the queue is empty. If we dequeue an empty queue, we should also get

In the dequeue() function of Queue.java, we do not check if the queue is empty. If we dequeue an empty queue, we should also get an error. Implement the empty 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

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!