This is my program to implement queue using array. I am not getting the correct output when I am calling dequeue for the first time, but it is showing the correct output for the rest of the dequeue operations (again after showing some weird value).
The output for this program is as follows:
136
14
13
1342222119
-1
-1
This is what I have tried:
#include<stdio.h>
#include<stdlib.h>
struct queue {
int capacity;
int rear;
int front;
int *array;
};
struct queue* createqueue(int capacity)
{
struct queue* nque = (struct queue*)malloc(sizeof(struct queue));
nque->capacity = capacity;
nque->front = -1;
nque->rear = -1;
nque->array = (int*)malloc(sizeof(int)*capacity);
return nque;
}
int isempty(struct queue* amp)
{
return(amp->front == -1 && amp->rear == -1);
}
int isfull(struct queue* amp)
{
return (((amp->rear) + 1) % (amp->capacity) == amp->front);
}
void enqueue(struct queue* amp, int x)
{
if (isfull(amp))
return;
else if (isempty(amp))
{
amp->rear = 0;
amp->front = 0;
}
else
{
amp->rear = (amp->rear + 1) % (amp->capacity);
}
amp->array[amp->rear] = x;
}
int dequeue(struct queue* amp)
{
if (isempty(amp))
return -1;
else if (amp->front == amp->rear)
{
amp->front = -1;
amp->rear = -1;
return(amp->array[amp->front]);
}
else
{
amp->front = ((amp->front) + 1) % (amp->capacity);
return(amp->array[amp->front]);
}
}
int main() {
struct queue* queue = createqueue(10);
enqueue(queue, 12);
enqueue(queue, 136);
enqueue(queue, 14);
enqueue(queue, 13);
enqueue(queue, 16);
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
printf("\n%d", dequeue(queue));
}
How to fix this issue?