#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node* next;
}node;
node* front,*rear;
void init()
{
front=rear=NULL;
}
int isEmpty()
{
if(front==NULL)
return 1;
return 0;
}
void enqueue(int element)
{
node* curr;
if(isEmpty())
{
front = (node*)malloc(sizeof(node));
front->next = NULL;
front->data = element;
rear = front;
}
else
{
curr = (node*)malloc(sizeof(node));
curr->data = element;
curr->next = NULL;
rear->next = curr;
rear = curr;
}
}
void dequeue()
{
node* curr;
if(front==NULL)
printf("Can't dequeue.No element in queue");
else
{
if(front->next==NULL) //last element present
{
free(front);
init();
}
else
{
curr = front->next;
free(front);
front = curr;
}
}
}
void display()
{
node* curr;
if(isEmpty())
printf("\nQueue is empty");
else
{
printf("\n");
for(curr=front;curr!=NULL;curr=curr->next)
printf("%d ",curr->data);
}
}
int main()
{
enqueue(1);
display();
enqueue(2);
display();
enqueue(3);
display();
dequeue();
display();
return 0;
}
No comments:
Post a Comment