Introduction
A queue is a data structure that stores items in a First In First Out (FIFO) manner. This means that the first item to be inserted into the queue is the first one to be removed.
we can implement a queue using an array or a linked list. In this article, we will implement a queue using a linked list.
we will use the concepts of templates, pointers, and object-oriented programming.
Queue Operations
- Enqueue: Adds an item to the queue.
- Dequeue: Removes an item from the queue.
- Peek: Returns the front item of the queue without removing it.
- IsEmpty: Checks if the queue is empty.
Queue Implementation
we will start by defining all the methods and variables that we will need in our queue class.
Queue class
The Queue class has two private pointers, head and tail, which point to the first and last nodes in the queue respectively. It also has a public integer length which keeps track of the number of elements in the queue. To make the queue generic, we will use templates.
The constructor initializes an empty queue. head and tail are set to nullptr and length is set to 0.
Node Structure
The Queue is implemented using a linked list. Each node in the list contains a value of a generic type T and a pointer to the next node. The Node structure is defined within the Queue class and is private, meaning it can only be accessed by members of the Queue class.
Node constructor takes two arguments, the value of the node and a pointer to the next node. The default value of the next pointer is nullptr. Sets the value and next variables to the passed arguments.
Enqueue
This function adds an element to the end of the queue. If the queue is empty, a new node is created and both head and tail point to it. If the queue is not empty, a new node is created and added to the end of the queue, and tail is updated to point to this new node. The length is incremented by 1.
Dequeue
This function removes an element from the front of the queue. If the queue is empty, it returns a default-constructed value of type T. If the queue is not empty, it saves the value of the head node, updates head to point to the next node, deletes the old head node, and decrements length by 1. If the queue becomes empty after the dequeue operation, tail is also set to nullptr.
Peek
This function returns the value of the front element without removing it. If the queue is empty, it returns a default-constructed value of type T.
IsEmpty
This function checks if the queue is empty. It returns true if length is 0, and false otherwise.