#include #include "queue.h" struct s_link { unsigned value; struct s_link *next; }; typedef struct s_link link; struct s_queue { link *first; /* sortie */ link *last; /* entrée */ }; /* crée une file vide */ queue create_queue(void) { return (queue) calloc(1, sizeof(struct s_queue)); } /* ajoute un élément à la file. Renvoie 0 en cas d'échec */ int enqueue(queue the_queue, unsigned the_value) { link *new = (link*) malloc(sizeof(link)); if (new == NULL) { return 0; } new->value = the_value; new->next = NULL; if (the_queue->last == NULL) { the_queue->first = new; } else { the_queue->last->next = new; } the_queue->last = new; return 1; } /* renvoie 1 si la file est vide */ int empty(queue the_queue) { return the_queue->first == NULL; } /* retire un élément de la file. Renvoie l'élément retiré, ou -1 en cas d'échec */ long dequeue(queue the_queue) { if(the_queue->first == NULL) { return -1; } link l = *(the_queue->first); free(the_queue->first); the_queue->first = l.next; if (the_queue->first == NULL) { the_queue->last = NULL; } return l.value; } /* détruit une file en libérant les ressources associées */ void destroy_queue(queue the_queue) { link *current, *saved; current = the_queue->first; while(current != NULL) { saved = current->next; free(current); current = saved; } free(the_queue); }