Skip to content

Instantly share code, notes, and snippets.

@Prince781
Created January 12, 2015 03:44
Show Gist options
  • Save Prince781/26eccf959c8deab48246 to your computer and use it in GitHub Desktop.
Save Prince781/26eccf959c8deab48246 to your computer and use it in GitHub Desktop.
A queue implementation in C
#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
struct queue *queue_new(void)
{
struct queue *q;
q = malloc(sizeof(struct queue));
q->base = NULL;
q->size = 0;
return q;
}
void queue_push(struct queue *q, void *elem)
{
struct queue_elem **qeptr;
for (qeptr = &q->base; *qeptr != NULL; qeptr = &(*qeptr)->next);
*qeptr = malloc(sizeof(struct queue_elem));
(*qeptr)->next = NULL;
(*qeptr)->data = elem;
++q->size;
}
void *queue_pop(struct queue *q)
{
struct queue_elem *top;
void *data;
if (queue_empty(q)) {
fprintf(stderr, "%s: queue is empty\n", __func__);
return NULL;
}
top = q->base;
q->base = top->next;
data = top->data;
free(top);
--q->size;
return data;
}
void queue_destroy(struct queue *q)
{
while (!queue_empty(q))
queue_pop(q);
free(q);
}
#ifndef _QUEUE_H
#define _QUEUE_H
struct queue_elem {
struct queue_elem *next;
void *data;
};
struct queue {
struct queue_elem *base;
int size;
};
struct queue *queue_new(void);
void queue_push(struct queue *q, void *elem);
void *queue_pop(struct queue *q);
#define queue_empty(q) ((q)->size == 0)
void queue_destroy(struct queue *q);
#endif /* _QUEUE_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment