C language tail queue tailq is Shared using examples

  • 2020-04-02 02:08:36
  • OfStack

The structure definition and operation of queue and list are completed in 'sys/queue.h', and the following four data structures are mainly defined:

1 single-linked lists
2 single-linked tail queue
List 3 (lists)
4 tail queues

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140128114543.jpg? 201402811474 ">

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201401/20140128114556.jpg? 2014028114736 ">

Use the sample


#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>

struct tailq_entry {
 int value;
 TAILQ_ENTRY(tailq_entry) entries;
};
//Define the head of the queue
TAILQ_HEAD(, tailq_entry) my_tailq_head;
int main(int argc, char  *argv[])
{
 //Defines a pointer to a struct
 struct tailq_entry *item;
 //Define another pointer
 struct tailq_entry *tmp_item;

 //Initialize queue
 TAILQ_INIT(&my_tailq_head);
 int i;
 //Add 10 elements to the queue
 for(i=0; i<10; i++) {
  //Request memory space
  item = malloc(sizeof(*item));
  if (item == NULL) {
   perror("malloc failed");
   exit(-1);
  }
  //Set the value
  item->value = i;
  
  TAILQ_INSERT_TAIL(&my_tailq_head, item, entries);
 }
 //Traverse the queue
 printf("Forward traversal: ");
 TAILQ_FOREACH(item, &my_tailq_head, entries) {
  printf("%d ",item->value);
 }
 printf("n");
 //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);
   //Free unwanted memory units
   free(item);
   break;
  }
  tmp_item = TAILQ_NEXT(item, entries);
 }
 TAILQ_FOREACH(item, &my_tailq_head, entries) {
  printf("%d ", item->value);
 }
 printf("n");
 //Empty the queue
 while (item = TAILQ_FIRST(&my_tailq_head)) {
  TAILQ_REMOVE(&my_tailq_head, item, entries);
  free(item);
 }
 //Check to see if it is empty
 if (!TAILQ_EMPTY(&my_tailq_head)) {
  printf("tail queue is  NOT empty!n");
 }
 return 0;

}


Related articles: