Queue

Overview

Similarly to a Stack, a Queue is a linear data structure where the elements are inserted and removed in a specific order. It follows the FIFO (First In, Last Out) principle, where the first added element is the first one to be removed.

Data Structures - Queue

Queue Types

  • Input Restricted Queue. A queue, where the elements can be retrieved only from one end, but deletion can be done from both ends.
  • Output Restricted Queue. A queue, where the elements can be retrieved from both ends, but deletion can be done from only one end.
  • Circular Queue. A queue, where the last position is connected back to the first position.
  • Dequeue (Double-Ended Queue). Insertion and deletion operations can be performed for both ends.
  • Priority Queue. A queue, where the elements are retrieved based on their priority, not the insertion order.

Operations

OperationDescriptionTime Complexity
EnqueueAdd an element to the end of the queueO(1)
DequeueRetrieve and remove an element from the start of the queueO(1)
PeekRetrieve an element from the start of the queue without removing itO(1)

Advantages

  • Queues are used in the implementation of other data structures
  • Queues provide constant time complexity for its core operations

Disadvantages

  • Not suitable for searching accessing its middle elements
  • Limited size on an array implementation
  • Additional space required on a linked list implementation

Use Cases

  • Operating systems (CPU, disk scheduling)
  • Breath-First Search
  • To handle multiple producers by a single consumer

Implementation

Custom Implementation

A Queue can be represented as an array or a linked list. In the case of an array, we need to store the indexes of the first and last stored elements. For the linked list, we need to have pointers to the head and tail list nodes.

Built-in Examples

Resources