Wednesday 20 August 2014

Filled Under:

C Program To implement Queue using Linked list

Share


Queue is a linear data structure, in which the first data element inserted from one end called REAR (also called tail),and the deletion of exisiting element takes place from the other end called FRONT(also called head). This make queue is FIFO data structure,which means that element inserted first will also be removed first

Example of C Program To implement Queue using Linked list

#include<stdio.h>
struct node
{
 int info;
 struct node *link;
}*front = NULL, *rear = NULL;

void insert();
void delet();
void display();
int item;

main()
{
 int ch;
 do
 {
  printf("nn1.tInsertn2.tDeleten3.tDisplayn4.tExitn");
  printf("nEnter your choice: ");
  scanf("%d", &ch);
  switch(ch)
  {
   case 1:
   insert();
   break;
   
   case 2:
   delet();
   break
   
   case 3:
   display();
   break;
   
   case 4:
   exit(0);
   
   default:
   printf("nnInvalid choice. Please try again...n");
  }
 } while(1);
 getch();
}

void insert()
{
 printf("nnEnter ITEM: ");
 scanf("%d", &item);
 if(rear == NULL)
 {
  rear = (struct node *)malloc(sizeof(struct node));
  rear->info = item;
  rear->link = NULL;
  front = rear;
 }
 else
 {
  rear->link = (struct node *)malloc(sizeof(struct node));
  rear = rear->link;
  rear->info = item;
  rear->link = NULL;
 }
}

void delet()
{
 struct node *ptr;
 if(front == NULL)
 printf("nnQueue is empty.n");
 else
 {
  ptr = front;
  item = front->info;
  front = front->link;
  free(ptr);
  printf("nItem deleted: %dn", item);
  if(front == NULL)
  rear = NULL;
 }
}

void display()
{
 struct node *ptr = front;
 if(rear == NULL)
 printf("nnQueue is empty.n");
 else
 {
  printf("nn");
  while(ptr != NULL)
  {
   printf("%dt",ptr->info);
   ptr = ptr->link;
  }
 }
}