Tuesday 21 August 2012

program to implement queue using linked list

#include<stdio.h>
#include<malloc.h>
void disp();
void pop();
void add();
struct node
{
    int info;
    struct node *link;

}*rear,*front=NULL;
main()
{
int ch;
while(1)
{
printf("\n.............MENU..............\n");
printf("\n1.push element to queue\n");
printf("2.dispaly\n");
printf("3.delete element from queue\n");
printf("4.exit\n");
printf("enter your choice:");
scanf("%d",&ch);
switch(ch)

{
    case 1:
    add();
    break;
    case 2:
    disp();
    break;
    case 3:
    pop();
    break;
    case 4:
    exit(1);
}

}

}

void add()
{
    struct node *tmp;
    int data;
    printf("enter the element:");
    scanf("%d",&data);
    tmp=malloc(sizeof(struct node ));
    tmp->info=data;
    tmp->link=NULL;
    if(front==NULL)

        front=tmp;
     else
        rear->link=tmp;
        rear=tmp;
}
void disp()
{
    struct node *tmp;

    if(front==NULL)
    printf("the queue is empty\n");
    else
    {
        printf("the elements:\n");
      tmp=front;

    while(tmp!=rear)
    {

        printf("<--%d",tmp->info);
        tmp=tmp->link;
    }
        printf("<-%d\n",tmp->info);
    }
}
void pop()
{

    struct node *tmp;
    if(front==NULL)
    printf("underflow\n");
    else
    {

      tmp=malloc(sizeof(struct node));
      tmp=front;
      printf("\ndeleted element is=%d",tmp->info);
      front=front->link;
      free(tmp);
    }
}

                                        OUTPUT
.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:1
enter the element:1

.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:1
enter the element:2

.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:1
enter the element:3

.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:2
the elements:
<--1<--2<-3

.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:3

deleted element is=1
.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:3

deleted element is=2
.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:3

deleted element is=3
.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:3
underflow

.............MENU..............

1.push element to queue
2.dispaly
3.delete element from queue
4.exit
enter your choice:4

Process returned 1 (0x1)   execution time : 48.970 s
Press any key to continue.

No comments:

Post a Comment