Are there standard Queue implementations for C?
Is there any Queue data structure implementation that "comes" with C or will I have to develop my own (this is for a school project, thus I must use something that either exists in the standard gcc installation or have to 开发者_如何学Goimplement one by myself!)
What about other general data structures like Linked Lists, Stacks, etc?
Try this. Unix comes with several kinds of linked lists - you can use one of them to create other possibly list based structures such as a stack.
man queue
No. But here is a very simple implementation:
typedef struct node {
int val;
struct node *next;
} node_t;
void enqueue(node_t **head, int val) {
node_t *new_node = malloc(sizeof(node_t));
if (!new_node) return;
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
int dequeue(node_t **head) {
node_t *current, *prev = NULL;
int retval = -1;
if (*head == NULL) return -1;
current = *head;
while (current->next != NULL) {
prev = current;
current = current->next;
}
retval = current->val;
free(current);
if (prev)
prev->next = NULL;
else
*head = NULL;
return retval;
}
Complete source here
You must implement your own. C has very little in terms of data structures and forces you to resort to arguable tricks to implement abstract data types: see an article titled “Incomplete types as abstractions” if you can find it, or see how the principles are applied in, say, PolarSSL's bignum.h file. C++ on the other hand is supposed to allow you to do pretty much everything you can do in C and give you ways to implement abstract data structures.
You could use a named pipe. It's a FIFO data structure and is part of the posix standard. If all your want is enque to the back and remove from the front it will work. You'll need to keep track of message boundaries by hand though, perhaps by having the first element be the number of bytes in the next message.
Use BSB lib. sys/queue.h and sys/tree.h have implementations of various lists and trees.
Not exacly standard, but many systems have bsd/sys/queue.h
and bsd/sys/tree.h
that are macro-based libraries.
See the documentation here.
GLib (not to be confused with glibc) implements many common data structures including double-ended queues. Unlike FreeBSD's macro-based queues, GLib's GQueues are based on functions which may be easier to debug and type check.
https://developer.gnome.org/glib/stable/glib-Double-ended-Queues.html
You have to implement your own data structures, but there exist many data structure libraries out there.
精彩评论