Queue using Linked List
The major problem with the queue implemented using an array is, It will work for an only fixed number of data values. That means, the amount of data must be specified at the beginning itself. Queue using an array is not suitable when we don't know the size of data which we are going to use.
A queue data structure can be implemented using a linked list data structure. The queue which is implemented using a linked list can work for an unlimited number of values. That means, queue using linked list can work for the variable size of data (No need to fix the size at the beginning of the implementation). The Queue implemented using linked list can organize as many data values as we want.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is always pointed by 'front'.
Algorithm
Node structure for Queue :
struct node
{
int data;
struct node *next;
};
To point the front and rear node :
struct node *front = NULL, *rear = NULL;
Enqueue function :
Enqueue function will add the element at the end of the linked list.
Using the rear pointer, we can track the last inserted element.
- Declare a new node and allocate memory for it
- If front == NULL, make both front and rear points to the new node.
- Otherwise,add the new node in rear->next.
make the new node as the rear node. i.e. rear = new node
void enqueue(int val)
{
struct node *newNode = malloc(sizeof(struct node));
newNode->data = val;
newNode->next = NULL;
//if it is the first node
if(front == NULL && rear == NULL)
//make both front and rear points to the new node
front = rear = newNode;
else
{
//add newnode in rear->next
rear->next = newNode;
//make the new node as the rear node
rear = newNode;
}
}
Dequeue function :
Dequeue function will remove the first element from the queue.
- Check whether the queue is empty or not
- If it is the empty queue (front == NULL) We can't dequeue the element.
- Otherwise, Make the front node points to the next node. i.e front = front->next; if front pointer becomes NULL, set the rear pointer also NULL. Free the front node's memory.
void dequeue()
{
//used to freeing the first node after dequeue
struct node *temp;
if(front == NULL)
printf("Queue is Empty. Unable to perform dequeue\n");
else
{
//take backup
temp = front;
//make the front node points to the next node
//logically removing the front element
front = front->next;
//if front == NULL, set rear = NULL
if(front == NULL)
rear = NULL;
//free the first node
free(temp);
}
}