In the previous screen, we saw how to implement a queue using the LinkedList
class in Java. Another common way to implement a queue is using arrays.
Array Implementation of Queues
The array implementation of queues involves using an array to store the items in the queue. Two pointers, front
and rear
, are used to keep track of the first and last elements of the queue, respectively.
Here's an example of how to implement a queue using an array in Java:
1import java.util.Arrays;
2
3public class ArrayQueue {
4 private static final int DEFAULT_CAPACITY = 10;
5 private int[] queue;
6 private int front;
7 private int rear;
8
9 public ArrayQueue() {
10 queue = new int[DEFAULT_CAPACITY];
11 front = -1;
12 rear = -1;
13 }
14
15 // Other methods
16}
In this implementation, we have an array queue
to store the elements, and front
and rear
pointers to keep track of the first and last elements, respectively. The DEFAULT_CAPACITY
is used to specify the initial capacity of the array, and it can be adjusted as needed.
To enqueue an element, we increment the rear
pointer and add the element to the queue
. If the rear
pointer exceeds the array size, we resize the array to accommodate more elements.
To dequeue an element, we increment the front
pointer and return the element at the front
position. If the front
pointer exceeds the rear
, it means the queue is empty.
The advantage of the array implementation is that it provides constant-time access to the front and rear elements. However, it has a fixed size and can run out of space if more elements are added than the initial capacity.
Now that we have seen the array implementation of queues, let's move on to the next topic: linked list implementation of queues.
xxxxxxxxxx
}
import java.util.Arrays;
public class ArrayQueue {
private static final int DEFAULT_CAPACITY = 10;
private int[] queue;
private int front;
private int rear;
public ArrayQueue() {
queue = new int[DEFAULT_CAPACITY];
front = -1;
rear = -1;
}
public void enqueue(int item) {
if (rear == queue.length - 1) {
// Queue is full, resize the array
queue = Arrays.copyOf(queue, queue.length * 2);
}
queue[++rear] = item;
if (front == -1) {
front = 0;
}
}
public int dequeue() {
if (front == -1 || front > rear) {
// Queue is empty
throw new NoSuchElementException();