Queue C
Date: 2023-11-15Last modified: 2023-11-15
Table of contents
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// /usr/include/bsd/sys/queue.h
// /usr/include/x86_64-linux-gnu/sys/queue.h
#include <sys/queue.h>
From man queue
:
The <sys/queue.h>
header file provides a set of macros that define
and operate on the following data structures:
SLIST
singly linked listsLIST
doubly linked listsSTAILQ
singly linked tail queuesTAILQ
doubly linked tail queues
// The data type for the node
struct node {
char c;
// This macro does the magic to point to other nodes
TAILQ_ENTRY( node ) nodes;
};
int main( int arc, char *argv[] )
{
// This macro creates the data type for the head of the queue
// for nodes of type 'struct node'
TAILQ_HEAD( head_s, node ) head;
// Initialize the head before use
TAILQ_INIT( &head );
char string[] = "Hello World\n";
printf( "Put some nodes in the queue:\n" );
struct node *e = NULL;
int c = 0;
for( c = 0; c < strlen( string ); ++c ) {
printf( "Allocate memory for node %c\n", string[c] );
e = malloc( sizeof( struct node ) );
if( e == NULL ) {
fprintf( stderr, "malloc failed" );
exit( EXIT_FAILURE );
}
e->c = string[c];
// Actually insert the node e into the queue at the end
printf( "TAILQ_INSERT_TAIL %c\n", e->c );
TAILQ_INSERT_TAIL( &head, e, nodes );
e = NULL;
}
// print the queue
TAILQ_FOREACH( e, &head, nodes )
{
printf( "TAILQ_FOREACH %c\n", e->c );
}
// free the elements from the queue
while( !TAILQ_EMPTY( &head ) ) {
e = TAILQ_FIRST( &head );
printf( "TAILQ_REMOVE %c\n", e->c );
TAILQ_REMOVE( &head, e, nodes );
printf( "Release memory from node %c\n", e->c );
free( e );
e = NULL;
}
return EXIT_SUCCESS;
}