Add diep() function
[eleutheria.git] / genstructs / linkedlist.c
blobfedafd37ae8d497bb6c90c1964040bf0347ed8ab
1 /* compile with:
2 gcc linkedlist.c -o linkedlist -Wall -W -Wextra -ansi -pedantic */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/queue.h>
9 LIST_HEAD(listhead, entry) head;
10 struct listhead *headp;
12 struct entry {
13 LIST_ENTRY(entry) entries;
14 const char *str;
15 } *np, *n;
17 int main(void)
19 const char *str[] = { "this", "is", "a", "linked", "list" };
20 unsigned int i;
22 /* Initialize list */
23 LIST_INIT(&head);
24 headp = &head;
26 /* Populate list with str[] items */
27 for (i = 0; i < sizeof str / sizeof *str; i++) {
28 if ((n = malloc(sizeof(struct entry))) == NULL) {
29 perror("malloc");
30 goto CLEANUP_AND_EXIT;
32 n->str = str[i];
34 if (i == 0)
35 LIST_INSERT_HEAD(&head, n, entries);
36 else
37 LIST_INSERT_AFTER(np, n, entries);
38 np = n;
41 /* Traverse list */
42 LIST_FOREACH(np, &head, entries)
43 printf("%s\n", np->str);
45 CLEANUP_AND_EXIT:;
46 /* Delete all elements */
47 while (LIST_FIRST(&head) != NULL)
48 LIST_REMOVE(LIST_FIRST(&head), entries);
50 return EXIT_SUCCESS;