I've never written a queue before and literally just took the concepts and tried to code something up. I decided to write a basic integer queue and as an example/driver I use a queue of size 5 which implements insert(), delete(), and display().
Please critique these implementations and comment if there should be any additions or modifications. The reason for the simplicity is that I'm mostly concerned that I got the concepts correct at this point. This is not the most robust queue by any means.
#include <stdio.h>
#include <stdlib.h>
#define ERR(msg) fprintf(stderr, "%s\n", msg)
#define QUEUE_SIZE 5
static size_t const front = 0;
static size_t rear = 0;
int queue[QUEUE_SIZE];
int insert(int num);
int delete(void);
void display(void);
int main(void)
{
insert(5);
insert(8);
insert(58);
insert(9);
insert(10);
display();
delete();
display();
delete();
display();
delete();
display();
delete();
display();
return EXIT_SUCCESS;
}
int insert(int num)
{
if((rear + 1) > QUEUE_SIZE)
{
ERR("Queue full, cannot insert item.");
return -1;
}
queue[rear++] = num;
return 0;
}
int delete(void) // Deletes the front one
{
if(rear == front)
{
ERR("Cannot delete from empty queue.");
return -1;
}
size_t i;
for(i = front; (i+1) < QUEUE_SIZE; i++)
{
queue[i] = queue[i+1];
}
rear--;
return 0;
}
void display(void)
{
size_t i;
for(i = front; i < rear; i++)
{
printf("%d\t", queue[i]);
}
putchar('\n');
return;
}