In data structure, enqueue and dequeue are two fundamental operations that are commonly used in implementing various types of data structures, such as queues and priority queues. These operations allow us to add elements to a data structure (enqueue) or remove elements from it (dequeue). Let’s take a closer look at what enqueue and dequeue mean and how they are used.

## Enqueue

The enqueue operation is used to insert an element into a data structure. It adds the new element at the end of the structure, following the FIFO (First-In-First-Out) principle. This means that the element that is added first will be the first one to be removed.

To enqueue an element, we need to consider the current state of the data structure. If it is empty, we simply insert the new element at the beginning. However, if there are already elements present, we need to add the new element at the end of the existing ones.

To illustrate this process, let’s consider a queue implemented using an array:

` ````
int queue[100]; // Assuming maximum size of 100
int front = -1;
int rear = -1;
void enqueue(int value) {
if(rear == 99) {
// Queue is full
return;
}
else if(front == -1 && rear == -1) {
// Queue is empty
front = rear = 0;
}
else {
rear++;
}
queue[rear] = value;
}
```

In this example, we maintain two indices: ‘front’ and ‘rear’ to keep track of where elements are present in the queue. When enqueueing an element, we increment ‘rear’ by 1 and assign the value to ‘queue[rear]’.

## Dequeue

The dequeue operation is used to remove an element from a data structure. It follows the FIFO principle, meaning that the element that has been in the data structure for the longest time will be removed first.

To dequeue an element, we need to consider the current state of the data structure. If it is empty, there are no elements to remove.

If there is only one element present, we simply remove it and update the indices accordingly. However, if there are multiple elements, we remove the first element and shift all remaining elements forward.

Let’s continue with our previous example of a queue implemented using an array:

` ````
int dequeue() {
int value;
if(front == -1 || front > rear) {
// Queue is empty
return -1;
}
else {
value = queue[front];
front++;
}
return value;
}
```

In this example, when dequeuing an element, we first check if ‘front’ is -1 (indicating an empty queue) or if ‘front’ has exceeded ‘rear’ (indicating no more elements are left). If neither condition is met, we assign ‘queue[front]’ to ‘value’, increment ‘front’ by 1, and then return ‘value’.

## Conclusion

Enqueue and dequeue are two essential operations in data structures that allow us to add and remove elements in a specific order. Enqueue adds elements at the end of a structure following the FIFO principle, while dequeue removes elements from the front of the structure following the same principle. Understanding these operations helps us implement various types of data structures effectively.