Mark As Completed Discussion

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.

  1. 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}
  1. 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.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment