Read this in other languages: English, Português
- What is a queue?
- Where are queues used?
- How to implement a queue?
- What are the basic operations of a queue?
A queue is a linear data structure in which elements are inserted at one end (the back of the queue) and removed from the other (the front of the queue). Due to this characteristic, queues are also known as FIFO (First-In First-Out) structures.
An analogy for this data structure is a grocery store queue. People enter the line at the end and wait their turn, while people at the front of the line leave and are served.
- Process management in operating systems. Tasks are added to a queue to be executed and tasks are removed from the queue when they are completed.
- Packet transmission in computer networks. Packets are added to a queue to be transmitted and are removed from the queue when they are delivered.
- Search algorithms in artificial intelligence. States are added to the queue to be explored and are removed from the queue when they are processed.
A queue q can be built with the following components:
q.cells[]: cells that store the elements of the queue.
q.first: a pointer that references the first element of the queue.
q.last: a pointer that references the last element of the queue.
q.length: an integer that counts the number of elements in the queue.
length()returns the length of a queue.enqueue()inserts an element at the end of a queue.dequeue()removes the element from the beginning of a queue.
- Return the value of
q.length.
- Update the last pointer of the queue
q.lastto reference a new cell. - Store the element
xin the cell referenced by the last pointer of the queue `q.last. - Increment by one the length counter of the queue q.length.
- Check if the queue
qis empty. If affirmative, go to step 2. Otherwise, go to step 3. - The queue is empty, so return
"empty queue". - Save in
xthe element referenced by the first pointer of the queueq.first. - Update the first pointer of the queue
q.firstto reference the cell before the current first of the queue. - Decrement by one the length counter of the queue
q.length. - Return the element
x.