EmbLogic's Blog

Implemented Queues with linked lists

#include<stdio.h>
#include<stdlib.h>
struct node
{
int val;
struct node*next;
}*front,*rear,*start=NULL;
int flag=0;
int get_choice(int*);
int create_node();
int enqueue();
int dequeue();
int display();
int main()
{
int choice=1;

while (choice)
{
printf(“+++++++++++++++++++MENU++++++++++++++++++++++\n                “);
printf(”                1.CREATE NODE                \n                “);
printf(”                2.ENQUEUE                    \n                “);
printf(”                3.DEQUEUE                    \n                “);
printf(”                4.DISPLAY                    \n                “);
printf(”                0.EXIT                       \n                “);
printf(“enter your choice\n”);
scanf(“%d”,&choice);
get_choice(&choice);
}}
int get_choice(int*choice)
{
switch(*choice)
{
case 1:create_node();break;
case 2:enqueue();break;
case 3:dequeue();break;
case 4:display();break;
case 0:exit(0);break;
}}
int create_node()
{
if(flag==0)
{
front=NULL;
rear=NULL;
printf(“queue created successfully”);
flag++;
}
else if(flag==1)
{
printf(“queue already created”);
}
}
int enqueue()
{
struct node*temp;
int i;
temp=(struct node*)malloc(sizeof(struct node));

if(flag==0)
{
printf(“queue not created\n”);
return 0;
}
else if(flag>5)
{
printf(“queue is full\n”);
return 0;
}
if(flag == 1)
{

printf(“enter the value to insert\n”);
scanf(“%d”,&(temp->val));
temp->next=NULL;
start=rear=temp;
flag++;
}
else if(flag>1 && flag!=1)
{
printf(“enter value”);
scanf(“%d”,&(temp->val));
temp->next=NULL;
rear->next=temp;
rear=rear->next;
flag++;
}

printf(“element inserted %d\n”,flag);

display();

}
int dequeue()
{
struct node*temp;
i:    if(flag == 0 )
{
printf(“queue empty\n”);
return 0;
}
if(front == rear)
{
goto o;
}
if(!front)
{
front=start->next;
printf(“%d is dequed\n”,start->val);

}
else if(front)
{
temp=front;
front=front->next;
printf(“%d is dequed\n”,temp->val);
}
else if(front == rear && front->next==NULL)
{

o:    printf(“%d is dequed\n”,front->val);
printf(“queue empty\n”);
front->next=NULL;
rear=front=start->next=NULL;
flag =0;
goto i;
}

display();

}
int display()
{
struct node*temp;
if(flag==0)
{    printf(“create a queue first\n”);
return 0;
}
if(!front)
temp = start;
else
temp = front;
while(temp!=NULL)
{
printf(“<-%d”,(temp)->val);
temp=temp->next;

}
printf(“\n”);

}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>