# Implementation of a Queue using Linked representation

Initially, the list is empty, so both the front and rear pointers are NULL. The insert function creates a new node, puts the new data value in it, appends it to an existing list, and makes the rear pointer point to it. A delete function checks whether the queue is empty, and if not, retrieves the data value of the node pointed to by the front, advances the front, and frees the storage of the node whose data value has been retrieved.

If the above strategy is used for creating a queue with four data values —10, 20, 30, and 40, the queue gets created as shown in following Figure.

```# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
};

void insert(struct node **front, struct node **rear, int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
/* creates new node
using data value
passed as parameter */
if(temp==NULL)
{
printf("No Memory available Error\n");
exit(0);
}
temp->data = value;
if(*rear == NULL)
{
*rear = temp;
*front = *rear;
}
else
{
*rear = temp;
}
}

void delete(struct node **front, struct node **rear, int *value)
{
struct node *temp;
if((*front == *rear) && (*rear == NULL))
{
printf(" The queue is empty cannot delete Error\n");
exit(0);
}
*value = (*front)->data;
temp = *front;
if(*rear == temp)
free(temp);
}

int main()
{
struct node *front=NULL,*rear = NULL;
int n,value;
do
{
do
{
printf("Enter the element to be inserted\n");
scanf("%d",&value);
insert(&front,&rear,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);

printf("Enter 1 to delete an element\n");
scanf("%d",&n);
while( n == 1)
{
delete(&front,&rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
getchar();
return 0;
}
```
Share

#### You may also like...

No © Loop and Break