Write a menu driven program to implement queue operations
such as Enqueue, Dequeue, Peek, Display of elements, isEmpty,
isFull using dynamic array.
#include <stdio.h>
#include <stdlib.h>
struct Queue
{
int *items;
int maxsize;
int front;
int rear;
int size;
};
struct Queue* createNewQueue(int size)
{
struct Queue *queue = NULL;
queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->items = (int*)malloc(size * sizeof(int));
queue->maxsize = size;
queue->front = 0;
queue->rear = -1;
queue->size = 0;
return queue;
}
int isEmpty(struct Queue *queue) {
return queue->size==0;
}
int Peek(struct Queue *queue)
{
if (isEmpty(queue))
{
printf("Queue is empty.\n");
}else{
return queue->items[queue->front];
}
}
int isFull (struct Queue *queue) {
return (queue->size == queue->maxsize);
}
void Enqueue(struct Queue *queue, int x)
{
if (isFull(queue) == 1)
{
printf("Queue is full.\n");
}else{
queue->rear = (queue->rear + 1) % queue->maxsize;
queue->items[queue->rear] = x;
queue->size++;
}
}
void Dequeue(struct Queue *queue)
{
if (isEmpty(queue))
{
printf("Queue is empty.\n");
}else{
queue->front = (queue->front + 1) % queue->maxsize;
queue->size--;
}
}
void Display (struct Queue *queue){
int i;
if (isEmpty(queue))
{
printf("Queue is empty.\n");
}else{
printf("All values: \n");
for(i = queue->front; i <= queue->rear; i++){
printf("%d\n", queue->items[i]);
}
}
}
int main()
{
struct Queue *queue = createNewQueue(5);
Enqueue(queue, 1);
Enqueue(queue, 2);
Enqueue(queue, 3);
Enqueue(queue, 4);
Display(queue);
Dequeue(queue);
Dequeue(queue);
Dequeue(queue);
Dequeue(queue);
Enqueue(queue, 5);
Enqueue(queue, 6);
if (isEmpty(queue)) {
printf("The Queue is empty");
}
else {
printf("The Queue is not empty");
}
getchar();
getchar();
return 0;
}
Comments
Leave a comment