Monday, May 23, 2011

DSA LAB PROGRAM. Write a program to illustrate the working of a Queue which is implemented using pointers. But note that the memory space occupied by a node in a linked representation is not exactly twice the space used by an element of array representation.


#include
#include
Struct node
{
int info;
struct node *link;
}*front,*rear,*newptr,*save;

main()
{
int ele,opt;
void insert(int);
int delete(struct node*);
void display(struct node*);
rear=NULL;
front=NULL;
while(1)
{
printf("\n Main menu ");
printf("\n\t1. Insert");
printf("\n\t2. Delete");
printf("\n\t3. Display");
printf("\n\t4. Exit");
printf("\n Enter ur choice");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("\n Enter element to insert");
scanf("%d",&ele);
insert(ele);
break;
case 2:
ele=delete(front);
printf("\n Deleted element=%d",ele);
break;
case 3:
display(queue);
break;
case 4:
exit(0);
break;
default :
printf("\n Wrong choice");
break;
}
}
}

void insert(int ele)
{
newptr=(struct node*)malloc(sizeof(struct node));
newptr->info=ele;
newptr->link=NULL;
if(rear==NULL)
{
rear=newptr;
front=newptr;
}
else
rear->link=newptr;
}

int delete(struct node *front)
{
int ele;
if(front==NULL)
{
printf("\n queue is empty");
return(0);
}
else
{
ele=front->info;
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
front=front->link;
return(ele);
}
}
 void display(struct node *front)
{
save=front;
while(save!=NULL)
{
printf(“\t%d”,save->info);
save=save->link;
}
}

Output:
Main menu
1.      Insert
2.      Delete
3.      Display
4.      Exit
Enter ur choice1

Enter element to insert424

Main menu
1.      Insert
2.      Delete
3.      Display
4.      Exit
Enter ur choice3
424
Main menu
1.      Insert
2.      Delete
3.      Display
4.      Exit
Enter ur choice2

Deleted element=424
Main menu
1.      Insert
2.      Delete
3.      Display
4.      Exit
Enter ur choice4

No comments:

Post a Comment