A queue can be represented using an array, especially when the size of the queue is fixed and known beforehand. To implement a queue using an array, we typically use the following components:
- An array to store the elements of the queue.
- Two pointers,
front
andrear
, to keep track of the front and rear elements of the queue.
class Queue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = self.rear = -1
def enqueue(self, item):
if self.rear == self.capacity - 1:
print("Queue is full")
elif self.front == -1 and self.rear == -1:
self.front = self.rear = 0
self.queue[self.rear] = item
else:
self.rear += 1
self.queue[self.rear] = item
def dequeue(self):
if self.front == -1:
print("Queue is empty")
elif self.front == self.rear:
temp = self.queue[self.front]
self.front = self.rear = -1
return temp
else:
temp = self.queue[self.front]
self.front += 1
return temp
def display(self):
if self.front == -1:
print("Queue is empty")
else:
print("Queue elements are:")
for i in range(self.front, self.rear + 1):
print(self.queue[i], end=" ")
print()
# Example usage:
q = Queue(5)
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.display() # Output: Queue elements are: 1 2 3
q.dequeue()
q.display() # Output: Queue elements are: 2 3
Algorithm To Insert Any Element In A Queue
- Check if the queue is already full by comparing rear to max – 1. if so, then return an overflow error.
- If the item is to be inserted as the first element in the list, in that case set the value of front and rear to 0 and insert the element at the rear end.
- Otherwise keep increasing the value of rear and insert each element one by one having rear as the index.
Algorithm
- Step 1: IF REAR = MAX – 1
Write OVERFLOW
Go to step
[END OF IF] - Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF] - Step 3: Set QUEUE[REAR] = NUM
- Step 4: EXIT
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// Creating a queue
Queue queue = new LinkedList<>();
// Enqueue elements into the queue
enqueueToQueue(queue, 10);
enqueueToQueue(queue, 20);
enqueueToQueue(queue, 30);
System.out.println("Queue before insertion:");
printQueue(queue);
// Inserting an element into the queue
insertIntoQueue(queue, 40);
System.out.println("Queue after insertion:");
printQueue(queue);
}
// Function to insert an element into the queue
private static void insertIntoQueue(Queue
queue, int element) {
queue.offer(element);
}
// Function to enqueue elements into the queue
private static void enqueueToQueue(Queue
queue, int element) {
queue.offer(element);
}
// Function to print the elements of the queue
private static void printQueue
(Queue queue) {
System.out.println("Queue: " + queue);
}
}