Now that we understand the basics of queues and their implementations, let's dive into the operations that we can perform on a queue.
The two fundamental operations of a queue are: enqueue and dequeue.
- Enqueue: This operation adds an element to the rear end of the queue. The enqueue operation is also known as insertion.
Here's the Java code for enqueue operation in a basic array implementation of a queue:
TEXT/X-JAVA
1void enqueue(int item) {
2 if (isFull()) {
3 throw new IllegalStateException("Queue is full");
4 }
5
6 rear = (rear + 1) % maxSize;
7 queue[rear] = item;
8 currentSize++;
9}- Dequeue: This operation removes an element from the front end of the queue. The dequeue operation is also known as deletion.
Here's the Java code for dequeue operation in a basic array implementation of a queue:
TEXT/X-JAVA
1int dequeue() {
2 if (isEmpty()) {
3 throw new NoSuchElementException("Queue is empty");
4 }
5
6 int item = queue[front];
7 front = (front + 1) % maxSize;
8 currentSize--;
9 return item;
10}It's important to note that both enqueue and dequeue operations have a time complexity of O(1) in a basic array implementation of a queue.
xxxxxxxxxx44
}class QueueOperations { private int[] queue; private int front; private int rear; private int maxSize; private int currentSize; public QueueOperations(int size) { maxSize = size; queue = new int[maxSize]; front = 0; rear = -1; currentSize = 0; } public void enqueue(int item) { if (isFull()) { throw new IllegalStateException("Queue is full"); } rear = (rear + 1) % maxSize; queue[rear] = item; currentSize++; } public int dequeue() { if (isEmpty()) { throw new NoSuchElementException("Queue is empty"); }OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


