# What Is Dequeue in Data Structure With Example?

//

Scott Campbell

A dequeue, also known as a double-ended queue, is a versatile data structure that allows insertion and deletion of elements from both ends. It is similar to a queue or a stack, but offers more flexibility by allowing operations at both the front and rear ends.

Operations on Dequeue:

• Insertion at Front: Add an element to the front of the dequeue.
• Insertion at Rear: Add an element to the rear of the dequeue.
• Deletion from Front: Remove an element from the front of the dequeue.
• Deletion from Rear: Remove an element from the rear of the dequeue.
• Accessing Front and Rear: Retrieve the value of the front and rear elements without modifying them.

An Example to Illustrate Dequeue:

Consider a scenario where you need to process a set of integers in a specific order. Let’s say you have the following sequence: [2, 4, 6, 8].

You want to process these numbers in such a way that even numbers are processed first, followed by odd numbers. To achieve this, you can use a dequeue.

Here’s how you can implement this using Python:

“`python
dequeue = []
“`

### Add elements to the front and rear:

“`python
dequeue.append(4) # Add 4 at rear
dequeue.appendleft(2) # Add 2 at front
dequeue.appendleft(6) # Add 6 at front
dequeue.append(8) # Add 8 at rear
“`

The state of the dequeue at this point is [6, 2, 4, 8].

### Process the elements:

You can now process the elements based on your desired order. In this case, you want to process even numbers first, followed by odd numbers.

“`python
while len(dequeue) > 0:
if dequeue[0] % 2 == 0:
even_number = dequeue.popleft()
print(“Processing even number:”, even_number)
else:
odd_number = dequeue.pop()
print(“Processing odd number:”, odd_number)
“`

The output of this code will be:

“`
Processing even number: 6
Processing even number: 2
Processing even number: 4
Processing even number: 8
“`

As you can see, the dequeue allows you to add elements at both ends and retrieve them accordingly. This flexibility makes it a useful data structure in scenarios where you need to manipulate elements from both directions.

Conclusion:

In summary, a dequeue is a data structure that allows insertion and deletion of elements from both ends. It offers more flexibility than a queue or stack by allowing operations at the front and rear. Dequeues are commonly used in scenarios where elements need to be processed in a specific order or when you need efficient access to both ends of the data structure.