Skip to content

Instantly share code, notes, and snippets.

@ataka
Created March 23, 2009 20:42
Show Gist options
  • Save ataka/83763 to your computer and use it in GitHub Desktop.
Save ataka/83763 to your computer and use it in GitHub Desktop.
queue sample program
# Queue sample program
# Author: Masayuki Ataka <[email protected]>
PROGRAM = queue
CC = gcc
CFLAGS = -W -Wall -g -O2 -std=c99
CPPFLAGS = -DDEBUG
all: $(PROGRAM)
$(PROGRAM): queue.o
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $^
queue.o: queue.c queue.h
#
# clean
#
RM = rm -f
clean:
$(RM) *~
$(RM) *.o
distclean: clean
$(RM) $(PROGRAM)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "queue.h"
/* ---------------------------------------- *\
Function declaration
\* ---------------------------------------- */
static bool is_empty(const queue_t* const q);
/* ---------------------------------------- *\
Functions
\* ---------------------------------------- */
queue_t* new_queue(void)
{
queue_t* q = (queue_t*)malloc(sizeof(queue_t));
if (q == NULL){
fprintf(stderr, "Allocation Error: queue\n");
return NULL;
}
q->tail = NULL;
q->head = q->tail;
return q;
}
/* Return TRUE if succeeded to malloc NEW node, else return FALSE. */
bool enqueue(const int n, queue_t* const queue)
{
node_t* new = (node_t*)malloc(sizeof(node_t));
if (new == NULL){
fprintf(stderr, "Allocation Error: node\n");
return false;
}
new->n = n;
new->prev = NULL;
if (is_empty(queue)){
queue->tail = new;
} else {
queue->head->prev = new;
}
queue->head = new;
return true;
}
/* Return 0 if queue is empty, else return dequeued value */
int dequeue(queue_t* const queue)
{
node_t* last = queue->tail;
if (is_empty(queue)){
fprintf(stderr, "QUEUE is empty\n");
return 0;
} else {
queue->tail = last->prev;
}
int n = last->n;
free(last);
return n;
}
void del_queue(queue_t* const queue)
{
if (!is_empty(queue)){
node_t* last = queue->tail;
queue->tail = last->prev;
free(last);
}
free(queue);
}
static bool is_empty(const queue_t* const q)
{
return q->tail == NULL;
}
#ifdef DEBUG
/* ---------------------------------------- */
int main(void)
{
queue_t* q = new_queue();
enqueue(5, q);
enqueue(4, q);
enqueue(3, q);
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
// queue is empty
// dequeue error check when queue is empty
printf("%d\n", dequeue(q));
enqueue(2, q);
printf("%d\n", dequeue(q));
// queue is empty
del_queue(q);
return 0;
}
#endif /* DEBUG */
#ifndef __QUEUE_H__
#define __QUEUE_H__
typedef struct node_tt
{
struct node_tt* prev;
int n;
} node_t;
typedef struct
{
node_t* head;
node_t* tail;
} queue_t;
queue_t* new_queue(void);
bool enqueue(const int n, queue_t* const queue);
int dequeue(queue_t* const queue);
void del_queue(queue_t* const queue);
#endif /* __QUEUE_H__ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment