The structure definitions and operations of queue and list are completed in ' sys/queue.h ', which mainly defines the following four types of data structures:
1 One-way list (single-linked lists)
2 one-way tail queues (single-linked tail queue)
3 List (lists)
4-tailed Queue (tail queues)
Using the sample
Copy Code code as follows:
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
/*
Defines a struct, it is just an element of the tail queue
It must contain a tailq_entry to point to the last and next element
*/
struct Tailq_entry {
int value;
Tailq_entry (tailq_entry) entries;
};
Define the head of a queue
Tailq_head (, tailq_entry) My_tailq_head;
int main (int argc, char *argv[])
{
To define a struct-body pointer
struct Tailq_entry *item;
Define a different pointer
struct Tailq_entry *tmp_item;
Initializing queues
Tailq_init (&my_tailq_head);
int i;
Add 10 elements to a queue
For (i=0 i<10; i++) {
Request Memory Space
item = malloc (sizeof (*item));
if (item = = NULL) {
Perror ("malloc failed");
Exit (-1);
}
Setting values
Item->value = i;
/*
Add elements to the tail of the queue
Parameter 1: A pointer to the queue header
Parameter 2: the element to add
Parameter 3: Variable name of structure body
*/
Tailq_insert_tail (&my_tailq_head, item, entries);
}
traversing queues
printf ("Forward traversal:");
Tailq_foreach (item, &my_tailq_head, entries) {
printf ("%d", item->value);
}
printf ("\ n");
To add a new element
printf ("Adding new Item after 5:");
Tailq_foreach (item, &my_tailq_head, entries) {
if (Item->value = = 5) {
struct Tailq_entry *new_item = malloc (sizeof (*new_item));
if (New_item = = NULL) {
Perror ("malloc failed");
Exit (Exit_failure);
}
New_item->value = 10;
Insert an Element
Tailq_insert_after (&my_tailq_head, item, New_item, entries);
Break
}
}
Tailq_foreach (item, &my_tailq_head, entries) {
printf ("%d", item->value);
}
printf ("\ n");
Delete an element
printf ("Deleting Item with value 3:");
for (item = Tailq_first (&my_tailq_head); item!= NULL; item = tmp_item) {
if (Item->value = = 3) {
Delete an element
Tailq_remove (&my_tailq_head, item, entries);
Freeing unwanted memory cells
Free (item);
Break
}
Tmp_item = Tailq_next (item, entries);
}
Tailq_foreach (item, &my_tailq_head, entries) {
printf ("%d", item->value);
}
printf ("\ n");
Empty queues
while (item = Tailq_first (&my_tailq_head)) {
Tailq_remove (&my_tailq_head, item, entries);
Free (item);
}
To see if it is empty
if (! Tailq_empty (&my_tailq_head)) {
printf ("Tail queue is not empty!\n");
}
return 0;
}