Untitled

 avatar
unknown
c_cpp
2 years ago
1.2 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>

struct queue
{
    unsigned int back;
    unsigned int front;
    unsigned int size;
    unsigned int capacity;
    int* data;
};

struct queue* create_queue(unsigned int capacity)
{
    struct queue* q = (struct queue*)malloc(sizeof(struct queue));
    q->back = 0;
    q->front = 0;
    q->size = 0;
    q->capacity = capacity;
    q->data = (int*)malloc(capacity * sizeof(int));
    return q;
}

int queue_empty(struct queue* q)
{
    return q->size == 0;
}

int queue_full(struct queue* q)
{
    return q->size == q->capacity;
}

void queue_enqueue(struct queue* q, int value)
{
    if (queue_full(q))
    {
        printf("Queue overflow\n");
        return;
    }
    q->data[q->back] = value;
    q->back = (q->back + 1) % q->capacity;
    q->size++;
}

int queue_dequeue(struct queue* q)
{
    if (queue_empty(q))
    {
        printf("Queue underflow\n");
        return -1;
    }
    int value = q->data[q->front];
    q->front = (q->front + 1) % q->capacity;
    q->size--;
    return value;
}

int queue_size(struct queue* q)
{
    return q->size;
}

void free_queue(struct queue* q)
{
    free(q->data);
    free(q);
}
Editor is loading...