0% found this document useful (0 votes)
7 views16 pages

Java Queue Implementation Guide

Uploaded by

grojamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Java Queue Implementation Guide

Uploaded by

grojamani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

QUEUE :

A Queue is a linear data structure that follows the

FIFO rule (first in first out). in which elements are inserted


from one end called Rear and is removed from
the other end called Front.
The value of both Rear and Front is set to -1
initially and then these values are incremented
or decremented as the elements are inserted and
deleted.

Basic Queue Functions

A Queue must have the following functions:

 enqueue(obj) – insert element to the queue.

 dequeue() – remove and return the least recent item from

the queue.
 isEmpty() – returns true if the queue is empty, else false.

Applications of Queue

Queues are used in a lot of applications, few of them are:

 Queue is used to implement many algorithms like Breadth First Search (BFS),
etc.
 It can be also used by an operating system when it has to schedule jobs with
equal priority
 Customers calling a call center are kept in queues when they wait for
someone to pick up the calls

Queue Implementation in Java

Array representation of Queue


We can easily represent queue by using linear arrays. There are two
variables i.e. front and rear, that are implemented in the case of every
queue. Front and rear variables point to the position from where insertions
and deletions are performed in a queue.

Initially, the value of front and queue is -1 which represents an empty


queue. Array representation of a queue containing 5 elements along with
the respective values of front and rear, is shown in the following figure.

The above figure shows the queue of characters forming the English
word "HELLO". Since, However, the value of rear increases by one every
time an insertion is performed in the queue. After inserting an element
into the The value of rear will become 5 while the value of front remains
same.
After deleting an element, the value of front will increase from -1 to 0.
however, the queue will look something like following.
PROGRAM: QUEUE USING ARRAY
public class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

// check if the queue is full


boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

// if queue is full
if (isFull()) {
[Link]("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
[Link]("Insert " + element);
}
}

// delete element from the queue


int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
[Link]("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
element = items[front];

// if the queue has only one element


if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
[Link]( element + " Deleted");
return (element);
}
}

// display element of the queue


void display() {
int i;
if (isEmpty()) {
[Link]("Empty Queue");
}
else {
// display the front of the queue
[Link]("\nFront index-> " + front);

// display element of the queue


[Link]("Items -> ");
for (i = front; i <= rear; i++)
[Link](items[i] + " ");

// display the rear of the queue


[Link]("\nRear index-> " + rear);
}
}

public static void main(String[] args) {

// create an object of Queue class


Queue q = new Queue();

// try to delete element from the queue


[Link]();

// insert elements to the queue


for(int i = 1; i < 6; i ++) {
[Link](i);
}

// 6th element can't be added to queue because queue is full


[Link](6);

[Link]();

// deQueue removes element entered first i.e. 1


[Link]();
// Now we have just 4 elements
[Link]();

}
}

OUTPUT:
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
1 2 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4
-------------------
PROGRAM ;2
// Queue implementation in Java
public class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
[Link]("Queue is full");
} else {
if (front == -1)
front = 0;
rear++;
items[rear] = element;
[Link]("Inserted " + element);
}
}

int deQueue() {
int element;
if (isEmpty()) {
[Link]("Queue is empty");
return (-1);
} else {
element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
}
else {
front++;
}
[Link]("Deleted -> " + element);
return (element);
}
}

void display() {
int i;
if (isEmpty()) {
[Link]("Empty Queue");
} else {
[Link]("\nFront index-> " + front);
[Link]("Items -> ");
for (i = front; i <= rear; i++)
[Link](items[i] + " ");

[Link]("\nRear index-> " + rear);


}
}

public static void main(String[] args) {


Queue q = new Queue();

// deQueue is not possible on empty queue


[Link]();

// enQueue 5 elements
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);

// 6th element can't be added to because the queue is full


[Link](6);

[Link]();

// deQueue removes element entered first i.e. 1


[Link]();

// Now we have just 4 elements


[Link]();

}
}
Output: Queue is emptyInserted 1
Inserted 2
Inserted 3
Inserted 4
Inserted 5
Queue is full
Front index-> 0
Items ->
1 2 3 4 5 Rear index-> 4
Deleted -> 1

Front index-> 1
Items ->
2 3 4 5 Rear index-> 4

Program 3:
class queue
{
int data[];
int front, rear, maxsize;
public queue(int n)
{
data=new int[n];
front=rear=0;
maxsize=n;
}
public void addq(int n)
{
if(rear==maxsize)
{
[Link]("queue full");
return;
}
data[rear]=n;
rear++;
}
public int delq()
{
if (front==rear)
{
[Link]("queue empty");
return-1;
}
return data[front++];
}
public int count()
{
return(rear-front);
}
public String toString()
{
String s=new String();
for(int i=front;i<rear;i++)
s=s+data[i]+" ";
return s;
}
}

class usequeue
{
public static void main(String args[ ])
{
queue q1=new queue(5);
[Link](3);
[Link](78);
[Link](5);
[Link](51);
[Link](30);
[Link]("deleting"+[Link]());
[Link](q1);
[Link](73);
}
}

Output:

C:\roja>javac [Link]

C:\roja>java usequeue
queue full
deleting 3
78 5 51
queue full

C:\roja>

Common questions

Powered by AI

In an array-based queue in Java, inserting an element uses the 'enQueue' function. If the queue is full, it prints an error message. If the queue is not full and 'front' is at -1, it sets 'front' to 0 to denote that the queue now has elements. It then increments the 'rear' index and places the element at the 'rear' position in the array. This process ensures that elements are added in the order they are inserted, following the FIFO principle .

Initially, the queue is empty with 'front' = -1 and 'rear' = -1. After enQueue(1), 'front' becomes 0, 'rear' becomes 0, and the queue contents are [1]. After enQueue(2), 'rear' becomes 1, and the queue contents are [1, 2]. The deQueue operation removes the first element (1), setting 'front' to 1, so queue contents are [2]. After enQueue(3), 'rear' becomes 2, and the queue contents are [2, 3] with 'front' at 1 and 'rear' at 2 .

The 'deQueue' function checks if the queue is empty and returns an error if it is. If it is not empty, it removes the element at the 'front' position. If removing the element results in the queue having no more elements (i.e., 'front' exceeds 'rear'), it resets both 'front' and 'rear' to -1, indicating the queue is empty. This reset allows the queue to be reused without lingering indices, assuring that the queue signals it is empty .

A small fixed size for an array-based queue severely limits the queue's capacity to handle elements, often leading to overflow errors when more elements are inserted than the predefined size allows. This limitation makes such implementations impractical for dynamic applications where the number of elements is unpredictable, such as in server request handling or job scheduling systems. It requires careful size estimation and monitoring, potentially needing manual resizing or shifting to different data structures like linked lists to manage overflow and ensure efficient memory use and service .

The Java array-based queue implementation is efficient for sequential processing applications like print spooling due to its FIFO nature, which aligns well with task order processing. However, efficiency drops in scenarios requiring dynamic resizing or when facing fixed-size limits, leading to potential overflow without room for extra tasks. For continuous input like print spooling in busy environments, the requirement for predefined size makes dynamic reallocation or adoption of a circular queue imperative to maintain performance and avoid stalls due to fullness or vacancy inaccuracies .

The array-based queue implementation has a fixed size determined at creation, which can lead to wasted space or overflow if not handled properly; insertion and deletion operations are generally O(1). A linked-list-based queue is dynamically resizable, allowing it to grow as needed without a predefined limit, but at the cost of additional memory overhead for pointers. Operations like insertion and deletion are also O(1) in complexity. The key trade-off is the static size and potential overflow in arrays versus the increased memory overhead and dynamic flexibility of linked lists .

To convert the array-based queue to a circular queue, we need to update the 'enQueue' and 'deQueue' operations to use modulo arithmetic for index updates. When adding (enQueue), the 'rear' should be set to ('rear' + 1) % SIZE, allowing it to wrap around. Similarly, when removing (deQueue), 'front' should be updated the same way. The condition to check fullness also becomes 'front' == ('rear' + 1) % SIZE, to ensure correct overflow condition detection. These modifications ensure continuous usage of the array without logical breaks .

A queue determines it is full when the 'rear' index reaches the maximum size of the queue array (SIZE - 1) while 'front' is at 0. It is empty when both 'front' and 'rear' are set to -1. In the Java implementation using arrays, the 'isFull()' method checks if 'front' is 0 and 'rear' equals SIZE - 1, while 'isEmpty()' checks if 'front' is -1 to determine the queue's state .

The BFS algorithm uses a queue to explore nodes level by level. It begins with an initial node, enqueues it, and explores each adjacent node, enqueuing each unexplored node. Once a node's adjacent nodes are enqueued, the node itself is dequeued, ensuring nodes are processed in the exact order they are discovered, which is essential for level-order traversal. The FIFO nature of a queue is specifically suited for BFS because it maintains this order, ensuring that nodes are explored in the exact sequence needed to handle all nodes on the current level before proceeding to the next .

A circular queue treats the array as a loop and redefines the position of 'rear' to wrap around to the start of the array when it reaches the end, as long as there is available space at the beginning. This approach enables the reuse of previously vacated slots, optimizing memory usage and eliminating wasted space when the queue operates naturally as elements cycle through. It involves adjusting the index calculations for 'rear' and 'front' using modulo operations, thus increasing the effective capacity of the queue without increasing its array size, resolving the linear queue overflow problem without increasing array size .

You might also like