How to implement a Queue using a Linked List?

There are different ways to implement a Queue using different data structures like Array or linked list.
The primary difference from the array implementation is that Linked list Nodes are created dynamically and when required.

Function Insert()

Inserts an element into the queue. If rear is NULL, then the queue is empty and a single element is inserted. Otherwise, a node is inserted after rear with the required element and then that node is set to rear.


void Insert() {
  int val;
  cout<<"Insert the element in queue : "<<endl;
  if (rear == NULL) {
     rear = (struct node *)malloc(sizeof(struct node));
     rear->next = NULL;
     rear->data = val;
     front = rear;
  } else {
     temp=(struct node *)malloc(sizeof(struct node));

     rear->next = temp;
     temp->data = val;
     temp->next = NULL;
     rear = temp;

Function Delete()

If there are no elements in queue then it is underflow condition. If there is only one element in the queue that is deleted and front and rear are set to NULL. Otherwise, the element at front is deleted and front points to next element.


void Delete() {
  temp = front;
  if (front == NULL) {
  } else
  if (temp->next != NULL) {
     temp = temp->next;
     cout<<"Element deleted from queue is : "<<front->data<<endl;
     front = temp
  } else{
     cout<<"Element deleted from queue is : "<<front->data<<endl;
     front = NULL;
     rear = NULL;