summaryrefslogtreecommitdiff
path: root/circleq.c
blob: db6627103fc81a707203be9c4593668a95e300c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <sys/queue.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>

/*
 * circleq macro usage examples by Peter Werner <peterw@ifost.org.au>
 *
 * please see http://www.ifost.org.au/~peterw/queue.html for more info
 */

/*
 * our struct definition, with the circleq element to be referenced by f_link
 */

struct foo {
	int 	f_a;
	char 	f_b;
	CIRCLEQ_ENTRY(foo) f_link;
};

/*
 * the head of our circleq of struct foo's (see the manpage for more info)
 */
CIRCLEQ_HEAD(cqhead, foo) cq;

struct foo *alloc_foo(int a, char b);

int
main(void)
{
	struct foo *fp, *other;
	struct cqhead *cqp;

	CIRCLEQ_INIT(&cq);
	cqp = &cq;

	/*
	 * insert the elements, note the use of the f_link item
	 */
	fp = alloc_foo(1, 'a');
	CIRCLEQ_INSERT_HEAD(cqp, fp, f_link);

	fp = alloc_foo(2, 'b');
	CIRCLEQ_INSERT_TAIL(cqp, fp, f_link);

	/* 
	 * put this one after the head of the queue
	 */
	fp = alloc_foo(3, 'c');
	CIRCLEQ_INSERT_AFTER(cqp, CIRCLEQ_FIRST(cqp), fp, f_link);

	/*
	 * put this one in front of the one we just inserted
	 */
	other = alloc_foo(4, 'd');
	CIRCLEQ_INSERT_BEFORE(cqp, fp, other, f_link);


	/*
 	 * loop through the list
	 */
	CIRCLEQ_FOREACH(fp, cqp, f_link)
		printf("%d %c\n", fp->f_a, fp->f_b);

	/* 
	 * loop through the other way, note the use of cqhead
	 */
	printf("backwards!\n");
	CIRCLEQ_FOREACH_REVERSE(fp, cqp, f_link)
		printf("%d %c\n", fp->f_a, fp->f_b);

	/*
	 * free up our list 
	 */
	for (fp = CIRCLEQ_FIRST(cqp); fp != CIRCLEQ_END(cqp); fp = other) { 
		other = CIRCLEQ_NEXT(fp, f_link); 
		CIRCLEQ_REMOVE(cqp, fp, f_link);
		free(fp);
	}

	/*
	 * make sure
	 */
	if (CIRCLEQ_EMPTY(cqp))
		printf("List is empty!\n");
	else
		printf("List not empty!\n");

	return(0);
}

struct foo *
alloc_foo(int a, char b)
{
	struct foo *tmp;

	tmp = (struct foo *)malloc(sizeof(struct foo));
	if (tmp == NULL)
		err(1, "malloc");

	tmp->f_a = a;
	tmp->f_b = b;
	return(tmp);
}