Tuesday, October 7, 2008

Queue using Linkedlist

/* Implementation of queue using linkedlist */
#include
#include

void enqueue();
void dequeue();
void view();


struct node
{
int data;
struct node *next;

};

struct node *front=NULL;
struct node *rear=NULL;


int main()
{

int n;

do
{
printf("\n\n\n\n"
"1.enqueue an element\n"
"2.dequeue an element\n"
"3.view and count no.of element\n"
"4.end the program\n"
"\nenter your choice number : ");

scanf("%d",&n);


switch(n)
{
case 1:
enqueue();
break;

case 2:
dequeue();
break;

case 3:
view();
break;

case 4:
printf("\n\n\t--------------THANKS FOR USING------------\n\n");
break;

default:
printf("please enter the number 1 to 5 only :\n");

scanf("%d",&n);


}

}while(n<4);

return 0;
}




void enqueue()
{
int x;

struct node *temp;

temp=(struct node*) malloc (sizeof(struct node));

if(temp==NULL)
{

printf("\nqueue is overflow\n");

}

else
{
printf("\nenter the element : ");
scanf("%d",&x);

temp->data=x;
temp->next=NULL;

if( rear==NULL && front==NULL )
{
rear=temp;
front=temp;
}

else
{
rear->next=temp;
rear=temp;
}
}

return;

}



void dequeue()
{

int x;

if( front==NULL && rear==NULL)
{

printf("the queue is underflow\n");

}

else
{

x=front->data;
printf("\nthe dequeued element is -> %d",x);

if(front==rear)
{
front=NULL;
rear=NULL;
}

else
{
front=front->next;

}

}

return;

}



void view()
{

int count=1; // when temp = rear it come out from 'for' so

struct node *temp1;
temp1=front;

printf("\nthe elements in the queue are :\n");

for( ; temp1!=rear; temp1=temp1->next) //use do-while,condition:temp!=NULL
{
printf("\t\t\t\t%d\n",temp1->data);
count++;
}

printf("\t\t\t\t%d\n\n",temp1->data);

printf("the number of elements in the queue is %d\n\n",count);


return;

}

No comments: