Queues are abstract data structures that are similar to Stacks. A queue, unlike a stack, is open at both ends. One end is always used to input data (enqueue), whereas the other end is always used to delete data (dequeue). The queue employs the First-In-First-Out (FIFO) mechanism, which means that the data item stored first will be accessed first.
Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely erasing it from the memory. Here we shall try to understand the basic operations associated with queues −
- enqueue() − add (store) an item to the queue.
- dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient. These are −
- peek() − Gets the element at the front of the queue without removing it.
- isfull() − Checks if the queue is full.
- isempty() − Checks if the queue is empty.
peek() – Place the data at front of queue
Algorithm
begin procedure peek return queue[front] end procedure
isfull() – Used to check if the queue is full.
Algorithm
begin procedure isfull if rear equals to MAXSIZE return true else return false endif end procedure
isempty()- Checks if the queue is empty or not.
Algorithm
begin procedure isempty if front is less than MIN OR front is greater than rear return true else return false endif end procedure
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
- Step 1 − Check if the queue is full.
- Step 2 − If the queue is full, produce overflow error and exit.
- Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
- Step 4 − Add data element to the queue location, where the rear is pointing.
- Step 5 − return success.
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation −
- Step 1 − Check if the queue is empty.
- Step 2 − If the queue is empty, produce underflow error and exit.
- Step 3 − If the queue is not empty, access the data where front is pointing.
- Step 4 − Increment front pointer to point to the next available data element.
- Step 5 − Return success.