What Is Enqueue and Dequeue in Data Structure?

//

Scott Campbell

What Is Enqueue and Dequeue in Data Structure?

In data structures, enqueue and dequeue are two fundamental operations that are commonly used in queue implementations. A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle, meaning that the element inserted first is the one that will be removed first.

Enqueue Operation

The enqueue operation adds an element to the back of the queue. It is equivalent to inserting an element at the end of a line. When you enqueue an element, it becomes the last element in the queue.

To enqueue an element, you need to perform the following steps:

  1. Create a new node or allocate memory for the new element.
  2. Assign the value to be enqueued to this new node.
  3. If the queue is empty, set both front and rear pointers to point to this new node.
  4. If the queue is not empty, set the next pointer of the current rear node to point to this new node and update the rear pointer to point to this new node.

Dequeue Operation

The dequeue operation removes an element from the front of the queue. It is equivalent to removing an element from the front of a line. When you dequeue an element, it is permanently removed from the queue.

To dequeue an element, follow these steps:

  1. If there are no elements in the queue (i.e., if both front and rear pointers are NULL), display an error message stating that the queue is empty.
  2. If there is only one element in the queue, set both front and rear pointers to NULL to make the queue empty.
  3. If there are multiple elements in the queue, store the value of the element at the front of the queue in a temporary variable.
  4. Move the front pointer to point to the next node (i., update front to point to front->next).
  5. Release memory for the node that was previously at the front of the queue.

Summary

The enqueue operation adds an element to the back of a queue, while the dequeue operation removes an element from the front of a queue. These operations are essential for managing and manipulating data in a queue. By understanding how enqueue and dequeue work, you can effectively use queues in various applications such as process scheduling, breadth-first search algorithms, and more.

Remember that queues follow a FIFO order, ensuring that elements are processed in the same order they were inserted. By using enqueue and dequeue operations correctly, you can maintain this order and efficiently manage your data.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy