Sunday, October 2, 2011

Data Structure C program Queue using Linked List Dev c++

 #include <stdio.h>  
struct queue{
int data;
struct queue* next;
};
typedef struct queue* node;
node front=NULL,rear=NULL;
/* declaration of function */
void display();
void enqueue(node);
int dequeue();
void enqueue(node x)
{
if(front==NULL)//for inserting first element
{
rear=x;
front=x;
rear->next=NULL;//IMP
}
else//general case
{
rear->next=x;
rear=x;
rear->next=NULL;
}
}
int dequeue()
{
int x;
if(front==NULL)//if empty
{
printf("Empty queue\n");
return;
}
else//if not empty
{
node temp=front;
x=temp->data;
front=front->next;
free(temp);
}
if(front==NULL)//if deleted the last element
{
rear=NULL;
}
return x;
}
void display()
{
if(front==NULL)
{
printf("Queue Empty\n");
return;
}
node temp=front;
printf("Queue is:-\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
int main()
{
int ch;
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
scanf("%d",&ch);
node temp;
int x;
while(ch!=4)
{
switch(ch)
{
case 1:
temp=(struct queue*)malloc(sizeof(struct queue));
printf("Enter data:");
scanf("%d",&(*temp).data);
enqueue(temp);
break;
case 2:
x=dequeue();
printf("Removed %d\n",x);
break;
case 3:
display();
break;
default:printf("WRONG CHOICE ENTER AGAIN\n");
}
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
scanf("%d",&ch);
}
}

No comments:

Post a Comment

Google+ Followers