Queues can implemented various ways
main three steps are
1> using linked list
2> using array
3> stack
lets see with the help of linked list
#include<stdio.h>
struct node1{
int value ;
struct node1 *next;
};
typedef struct node1 node ;
struct queue1{
node *front;
node *end;
};
typedef struct queue1 queue;
void insertion(queue *q,int data)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->value= data;
newnode->next= NULL;
if(isempty(q))
{
q->front= newnode;
q->end = newnode;
}
else{
newnode->next = q->end;
q->end=newnode;
}
}
int deletion(queue *qm)
{
int x;
if (isempty(qm))
{
printf("the queue is already empty");
}
else
{
node *temp=qm->end;
if (temp->next==NULL)
{
free(temp);
qm->front=NULL;
qm->end= NULL;
}
else
{
while(temp->next->next!=NULL)
{
temp=temp->next;
}
temp->next=NULL;
x= qm->front->value;
free(qm->front);
qm->front=temp;
return x;
}
}
}
isempty(queue *qm)
{
if(qm->end==NULL)
{
return 1;
}
else
return 0;
}
void print(queue qm )
{
while(qm.end!=NULL)
{
printf("%d\n",qm.end->value);
qm.end=qm.end->next;
}
}
void main()
{
queue q1;
q1.front=NULL;
q1.end=NULL;
insertion(&q1,10);
insertion(&q1,11);
insertion(&q1,15);
insertion(&q1,7);
print(q1);
int a =deletion(&q1);
print(q1);
}
main three steps are
1> using linked list
2> using array
3> stack
lets see with the help of linked list
#include<stdio.h>
struct node1{
int value ;
struct node1 *next;
};
typedef struct node1 node ;
struct queue1{
node *front;
node *end;
};
typedef struct queue1 queue;
void insertion(queue *q,int data)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->value= data;
newnode->next= NULL;
if(isempty(q))
{
q->front= newnode;
q->end = newnode;
}
else{
newnode->next = q->end;
q->end=newnode;
}
}
int deletion(queue *qm)
{
int x;
if (isempty(qm))
{
printf("the queue is already empty");
}
else
{
node *temp=qm->end;
if (temp->next==NULL)
{
free(temp);
qm->front=NULL;
qm->end= NULL;
}
else
{
while(temp->next->next!=NULL)
{
temp=temp->next;
}
temp->next=NULL;
x= qm->front->value;
free(qm->front);
qm->front=temp;
return x;
}
}
}
isempty(queue *qm)
{
if(qm->end==NULL)
{
return 1;
}
else
return 0;
}
void print(queue qm )
{
while(qm.end!=NULL)
{
printf("%d\n",qm.end->value);
qm.end=qm.end->next;
}
}
void main()
{
queue q1;
q1.front=NULL;
q1.end=NULL;
insertion(&q1,10);
insertion(&q1,11);
insertion(&q1,15);
insertion(&q1,7);
print(q1);
int a =deletion(&q1);
print(q1);
}
No comments:
Post a Comment