Merge branch 'exp-hash' into exp-fsm
[eleutheria.git] / genstructs / tailq.c
blob2714178a1bf9bb91977a16ba4fadab6ce4588456
1 /* compile with:
2 gcc tailq.c -o tailq -Wall -W -Wextra -ansi -pedantic */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/queue.h>
9 TAILQ_HEAD(tailhead, entry) head;
11 struct entry {
12 TAILQ_ENTRY(entry) entries;
13 const char *str;
14 } *np, *n;
16 int main(void)
18 const char *str[] = { "this", "is", "a", "double", "linked", "tailq" };
19 unsigned int i;
21 /* Initialize list */
22 TAILQ_INIT(&head);
24 /* Populate list with str[] items */
25 for (i = 0; i < sizeof str / sizeof *str; i++) {
26 if ((n = malloc(sizeof(struct entry))) == NULL) {
27 perror("malloc");
28 goto CLEANUP_AND_EXIT;
30 n->str = str[i];
32 TAILQ_INSERT_TAIL(&head, n, entries);
35 /* Traverse list forward */
36 TAILQ_FOREACH(np, &head, entries)
37 printf("%s %s", np->str,
38 TAILQ_NEXT(np, entries) != NULL ?
39 "-> " : "\n");
41 /* Traverse list in reverse order */
42 TAILQ_FOREACH_REVERSE(np, &head, tailhead, entries)
43 printf("%s %s", np->str,
44 TAILQ_PREV(np, tailhead, entries) != NULL ?
45 "-> " : "\n");
47 CLEANUP_AND_EXIT:;
48 /* Delete all elements */
49 while (TAILQ_FIRST(&head) != NULL) {
50 np = TAILQ_FIRST(&head);
51 TAILQ_REMOVE(&head, TAILQ_FIRST(&head), entries);
52 free(np);
55 return EXIT_SUCCESS;