Circular Queue Implementation

In the normal Queue, we can insert the data till the Queue gets full.

And rear will point to the last element. Therefore, no further addition of the elements can takes place. Even the elements get deleted, the further use of the free space can not be possible.

To overcome the problem of normal Queue, a new data structure is introduced called Circular Queue. In Circular Queue, the last position of the queue is connected back to first position. This structure allows the data insertion and deletion in circular manner, and allow to further use the free space of the Queue.

Graphical representation of circular Queue
Implementation of Circular Queue using Linked List

#include
#include

struct node
{
int data;
struct node *next;
}*front=NULL,*rear=NULL;

void Enqueue()
{
int n;
struct node *newNode=(struct node*)malloc(sizeof(struct node));
printf("Insert the data\n");
scanf("%d",&n);
newNode->data=n;
if(rear==NULL)
{
front=newNode;
rear=newNode;
newNode->next=newNode;
}
else
{
rear->next=newNode;
newNode->next=front;
rear=newNode;
}
}

void Dequeue()
{
if(front==NULL)
printf("Queue is empty");
else
{
struct node *temp;
temp=front;
printf("Dequeue element=%d",temp->data);
front=front->next;
rear->next=front;
free(temp);
}
}

void Display()
{
if(front==NULL)
printf("Queue is empty");
else
{
struct node *temp;
temp=front;
while(temp->next!=rear->next)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("%d->>%d\n",temp->data,temp->next->data);
}
}


int main()
{
int choice;
while(1)
{
printf("-----------Circular Queue-----------\n");
printf("1:Insert the data\n");
printf("2:Delete the data\n");
printf("3:Display\n");
printf("4:Exit\n");
printf("----------------------------------------\n");
printf("Enter the choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
     Enqueue();
     break;
case 2:
     Dequeue();
     break;
case 3:
     Display();
     break;
case 4:
     exit(0);
default:
    printf("invalid choice");
}
}
}

This code you can get it on below link....


https://drive.google.com/open?id=0B2O8tJ9QXc-3WnNkaGdSaW9EUm8

Comments

Popular posts from this blog

Types of Algorithm and Its Complexity Analysis

First Step of Problem Solving Using Data Structure and Algorithm

Asymptotic Notations