algoritmauzmanı
Sign in
TREN
5.1Queue with an Array
Lesson 5.1.2

Enqueue: adding at the rear

adds a new element at the rear of a . In an array queue that takes three short steps: check that there is room, add one to , write the value into that cell. is never touched. This lesson walks through the three steps and what happens when the array fills up.

What you will learn
  • Why enqueue starts with a full check
  • Why rear is increased first and the value written second
  • How C, Java and Python behave when you enqueue onto a full queue
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

rear is the index of the last element. The new element goes into the cell just to its right. So rear is increased by one first, and then the value is written to items[rear]. No element is shifted; the operation has the same shape as push on a stack.

Here is the difference: on a stack, adding and removing happen at the same end. In a queue, adding happens at the rear end and removing at the front end. Enqueue does not change front. An empty queue has front at 0 and rear at -1; the first enqueue moves rear to 0, and both indexes point at the same element.

The array has a fixed size. If rear is already at the last cell (CAPACITY - 1), there is no room to write and the queue is full. How this is reported depends on the language: in C the function returns false and the queue is unchanged. Java throws IllegalStateException and Python raises IndexError.

The full check does not look at front. Even if elements have left from the front, enqueue fails while rear is 4. This is the weak spot of a linear queue; the wasted cells lesson deals with it.

2Step by step

In the drawing, 5 is first added to a queue holding 3 and 8. Then the queue is filled up and one more enqueue is tried. The label above a cell marks front, the label below marks rear.

234308152639470front1rear2rear4rearfrontrear
  1. The start. The queue holds 3 and 8, front is 0 and rear is 1. enqueue(5) is called.
  2. isFull is checked: rear is 1 and the last index is 4. There is room, so it goes on.
  3. rear is increased by one and becomes 2. It now points at cell 2, which is free.
  4. The value is written to items[2]. 5 is at the rear of the queue.
  5. The C version returns true. The enqueue is done; front and the other elements did not change.
  6. 6 and 9 were added too. rear is 4: the last cell of the array is reached.
  7. enqueue(7) is tried. isFull returns true, so 7 is not written. C returns false, Java and Python throw an error. rear stays at 4.

#define CAPACITY 5 struct Queue {    int items[CAPACITY];    int front;    int rear;}; void create(struct Queue* q) {    q->front = 0;    q->rear = -1;} bool isFull(struct Queue* q) {    return q->rear == CAPACITY - 1;} bool enqueue(struct Queue* q, int value) {    if (isFull(q)) {        return false;  // queue is full    }    q->rear++;    q->items[q->rear] = value;    return true;}
class ArrayQueue {    int[] items;    int front = 0;    int rear = -1;     ArrayQueue(int capacity) {        items = new int[capacity];    }     boolean isFull() {        return rear == items.length - 1;    }     void enqueue(int value) {        if (isFull()) {            throw new IllegalStateException("queue is full");        }        rear++;        items[rear] = value;    }}
class ArrayQueue:    def __init__(self, capacity):        self.items = [None] * capacity        self.front = 0        self.rear = -1     def is_full(self):        return self.rear == len(self.items) - 1     def enqueue(self, value):        if self.is_full():            raise IndexError("queue is full")        self.rear += 1        self.items[self.rear] = value

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

One comparison, one increment and one write. The number of elements in the queue does not matter.

Memory
O(1)

The space was set aside in the array beforehand; enqueue asks for no new memory.

The capacity of this queue is fixed from the start. For a queue that grows without a limit, see enqueue with a linked list.

4Common mistake

A common mistake is swapping the order of the write and the increment:

q->items[q->rear] = value;  // wrong: writes firstq->rear++;

rear points at the last element. If you write first, the new value lands on top of the last element and that element is lost. On an empty queue rear is -1, so the write goes to items[-1], outside the array. The right order is rear++ first, then the write.

5Try it

A queue with capacity 5 has front = 0 and rear = 2. After enqueue(4), what are rear and front?

Show the answer

The answer is A. Enqueue only adds one to rear and writes 4 to items[3]. front does not change.

With front = 3 and rear = 4, what does enqueue(1) do?

Show the answer

The answer is B. In a linear queue the full check only looks at rear. Since rear is at the last index, the enqueue is refused; only a circular queue can use the free cells at the start.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.