Tuesday, June 19, 2012

C Language Program on Circular queue


A queue is called circular when the last node comes just before the first node in case of  queue implementation of linked list.There may a header node at the front.

# include < stdio.h>
# include < stdlib.h>
struct link
{
char info[20];
struct link *next;
};
struct link *p,*node,*new1,*start=NULL;
int x=0;
struct link *insert(struct link *nn)
{
if(x==0)
{
/*this will be a header node with no value in it's information part*/
fflush(stdin);
new1 = (struct link *) malloc(sizeof(struct link));
new1->next=new1;
node=new1;
x++;
}
else
{
x++;
node = nn;
p=start;
new1 = (struct link *) malloc(sizeof(struct link));
while(node->next!=node)
{
 node=node->next;
 p=p->next;
 }
 p->next=new1;
 new1->next=node;
 fflush(stdin);
printf("\n Input the node value: ");
gets(new1->info);
node=start->next;
 }
return node;
}
void display(struct link *node)
{
while (node->next!=node)
{
printf(" %s", node->info);
node = node->next;
}
}
struct link *del(struct link *nn)
{
node=nn;
if(node==NULL)
printf("\nDeletion not possible.");
else
{
p=node->next;
free(node);
node=p;
}
return node;
}
void main()
{
struct link *start=NULL;
int k = 0;
char choice='i';

/* at the start of the program you must create a location*/
clrscr();
do
{
  if(x!=0)
 {
printf("\nInsert->i Delete->d Quit->q:");
printf("\nInput the choice : ");
do
   {
choice = getchar();
choice = tolower(choice);
}while(strchr("idq",choice)==NULL);
 printf("Your choice is: %c ", choice);
}

/* end of the if block.At the first iteration of the do loop , no need to take choice from the user as firstly a node will be inserted as a header node. */

switch(choice)
{
case 'i' :
{
       start=insert(start);
  if(x==1) /* after creating the header node x becomes 1*/
  {
printf("\nHeader node is created.");
}
else
{
printf("\nQueue after inserting ");
display(start);
}/* no need to display when only the header node is created. */
break;
}
case 'd' :
{
start=del(start);
printf("\nQueue content after deleteion is as follows:\n");
display(start);
break;
}
case 'q':
{
k = 1;
}
}
} while(!k);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner