Wednesday, March 9, 2016

C program for queue implementation using link list

#include <stdio.h>
#include <stdlib.h>
//structure for the link list
struct node
{
    int info;
    struct node *ptr;
}*front,*rear,*temp,*front1;
//enq for insertion in queue
void enq(int data);
//deq for deletion from queue
void deq();
//for displaying queue data
void display();
//called once for the initialization
void create();
int count = 0;
void main()
{
    int no, ch, e;
    printf("\n 1 - Enque");
    printf("\n 2 - Deque");
    printf("\n 3 - Display");
    printf("\n 4 - Exit");
    create();
    while (1)
    {
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
   printf("Enter data : ");
   scanf("%d", &no);
   enq(no);
   break;
case 2:
   deq();
   break;
case 3:
   display();
   break;
case 4:
   exit(0);
   break;
default:
   printf("Wrong choice, Please enter correct choice  ");
   break;
}
    }
}
void create()
{
    front = rear = NULL;
}
void enq(int data)
{
    if (rear == NULL)
    {
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
    }
    else
    {
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
    }
    count++;
}
void display()
{
    front1 = front;
    if ((front1 == NULL) && (rear == NULL))
    {
printf("Queue is empty");
return;
    }
    while (front1 != rear)
    {
printf("%d ->", front1->info);
front1 = front1->ptr;
    }
    if (front1 == rear)
printf("%d->", front1->info);
}
void deq()
{
    front1 = front;
    //check if the queue is empty
    if (front1 == NULL)
    {
printf("\n Error: Trying to display elements from empty queue");
return;
    }
    else
if (front1->ptr != NULL)
{
   front1 = front1->ptr;
   printf("\n Dequed value : %d", front->info);
   free(front);
   front = front1;
}
else
{
   printf("\n Dequed value : %d", front->info);
   free(front);
   front = NULL;
   rear = NULL;
}
count--;
}

output
1 - Enque
2 - Deque
3 - Display
4 - Exit
Enter choice : 1
Enter data : 4
Enter choice :1
Enter data  8
Enter choice :3
4->3->
Enter choice :2
Dequed value : 4
Enter choice :1
Enter data : 5
Enter choice :3
3->5->
Enter choice :4

No comments:

Post a Comment