C语言中的基本数据结构库,例如Queue

Léo*_* 준영 7 c queue data-structures

问题:为队列找到正确的数据结构:

 #include <stdio.h>                                                                                                                                                             
 #include <stdlib.h>
 #include <stdarg.h>
 #include <time.h>

 int main(int argc, const char *argv[])
 {
     Queue q;
     ch ='A';
     for (int k = 0; int k < 4; int k++) {
         q.addQ(ch);
         ch++;
         q.addQ(ch);
         ch=q.front();
         q.removeQ();
     }
     return 0;
 }
Run Code Online (Sandbox Code Playgroud)

我试图编译它,但队列是未声明的:

$ gcc -o Qu_1 -g q_queue.c
q_queue.c: In function 'main':
q_queue.c:8: error: 'Queue' undeclared (first use in this function)
Run Code Online (Sandbox Code Playgroud)

问题:基本数据结构的库是什么,例如示例中的队列?

And*_*w Y 12

这看起来像TAILQ_*的一个很好的候选人?

#include <sys/queue.h>
Run Code Online (Sandbox Code Playgroud)

"man queue"将提供更多细节 - 那里有简单的列表,尾部队列和循环队列.这些是您需要在自己的结构上固定的宏,当然不是类.

你的场景的代码看起来像这样(我应该让add_to_queue返回一些代码来检查错误,并避免全局变量,但希望在这个例子中我会被原谅):

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

TAILQ_HEAD(tailhead, entry) head;

struct entry {
  char c;
  TAILQ_ENTRY(entry) entries;
};

void add_to_queue(char ch) {
  struct entry *elem;
  elem = malloc(sizeof(struct entry));
  if (elem) {
    elem->c = ch;
  }
  TAILQ_INSERT_HEAD(&head, elem, entries);
}

int main(int argc, char *argv[]) {
  char ch = 'A';
  int i;
  struct entry *elem;

  TAILQ_INIT(&head);
  for (i=0; i<4; i++) {
    add_to_queue(ch);
    ch++;
    add_to_queue(ch);

    elem = head.tqh_first;
    TAILQ_REMOVE(&head, head.tqh_first, entries);
    free(elem);
  }
  exit(0);
}
Run Code Online (Sandbox Code Playgroud)


Ree*_*sey 5

一个很好的选择是使用C通用库.这是在C++ STL上(松散地)建模的C库.它提供了队列结构,列表等.