Monday, April 2, 2012

cqueue using linkedlist


#include< stdio.h>

typedef struct cqueue
{
	int data;
	struct cqueue *next;
}list;

list *front,*rear;

list *push(list *);
list *pop(list *);
void display(list *);
int count(list *);
int menu(list *);

void main()
{
	int choice;

	front=(list *)malloc(sizeof(list));
	rear=(list *)malloc(sizeof(list));
	front->next=rear;
	rear->next=front;
	front->data=rear->data=NULL;

	while(1)
	{
		choice=menu(front);
		switch(choice)
		{
			case 1: rear=push(rear);break;
			case 2: front=pop(front);break;
			case 3:	display(front);getch();break;
			case 4: printf("\nno. of elements in quque : %d",count(front));getch();break;
			case 5: exit();
			default : printf("\nInvalid option\n");getch();
		}
	}
}

int menu(list *front)
{
	int choice;
	clrscr();
	printf("\nQueue elements\n\n");
	display(front);
	printf("\n\nMENU\n--------------\n1. add item\n2. delete item\n3. display items\n4. count items\n5. exit\n");
	printf("enter your choice : ");
	scanf("%d",&choice);
	return(choice);
}


list *push(list *rear)
{
	list *temp;
	int element;
	temp=(list *)malloc(sizeof(list));
	if(temp==NULL)
	{
		printf("\ninsufficient memory..\n");
		getch();
		exit();
	}
	else
	{
		printf("\nenter element to add : ");
		scanf("%d",&element);
		temp->data=element;
		rear->next=temp;
		temp->next=front;
		rear=temp;
	}
	return (rear);
}

list *pop(list *front)
{
	list *temp;

	if(front->next!=rear)
	{
		temp=front->next;
		free(front);
		front=temp;
	}
	else
	{
		printf("\nqueue empty\n");
		getch();
		return (front);
	}
	return (front);
}

int count(list *front)
{
	list *temp;
	temp=front;

	if(temp->next==rear)
		return 0;
	else
		return (1+count(temp->next));
}

void display(list *front)
{
	list *temp;
	temp=front->next;
	if(front->next==rear)
	{
		printf("\nqueue empty\n");
		return;
	}
	else
	{
		while(temp!=rear)
		{
			printf("%d ",temp->next->data);
			temp=temp->next;
		}
	}

}
	
		

No comments:

Post a Comment