Search This Blog

15 July, 2011

Queue using Linklist

#include<stdio.h>
#include<conio.h>
struct Node
{
int num;
struct Node*next;


};
struct Node*start=NULL;
void addToQueue(int num)
{
struct Node *t,*j;
t=(struct Node*)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
if(start==NULL)
{
start=t;
}
else
{
j=start;
while(j->next!=NULL)
{
j=j->next;
}
j->next=t;
}
}
int removeFromQueue()
{
struct Node *t;
int num;
if(start==NULL)return 0;//queue is empty
num=start->num;
t=start;
start=start->next;
free(t);
return num;


}
int isQueueEmpty()
{
return start==NULL;


}
void main()
{
int ch,num;
while(1)
{
printf("1 Add to queue\n");
printf("2 Remove from queue\n");
printf("3 Enter your choice");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter number to add to queue ");
scanf("%d",&num);
addToQueue(num);
printf("%d added to queue\n",num);
}
if(ch==2)
{
if(isQueueEmpty())
{
printf("Queue is empty\n");
}
else
{
num=removeFromQueue();
printf("%d removed from queue\n",num);
}
}
if(ch==3)
{
break;
}
}
}